为什么不抛出异常?(C#/NUnit/.NET 6)

wn9m85ua  于 2023-04-22  发布在  .NET
关注(0)|答案(1)|浏览(181)

我是C#的新手。
我正在尝试测试我的控制器,但我在让测试工作时遇到了麻烦。对于此测试,我想抛出我创建的异常InvalidQueryException。当我运行测试时,我得到以下消息:
“预期:<RedAeris.Exceptions.InvalidQueryException>但为:null”
为什么会出现这种情况?我怀疑实际上没有任何东西在运行,因为我的断点或print语句不起作用。
下面是控制器和测试:

using Microsoft.AspNetCore.Mvc;
using RedAeris.Constants;
using RedAeris.Exceptions;
using RedAeris.Models;
using RedAeris.Utilities;
using System.Text.Json;

namespace RedAeris.Controllers
{
    /// <summary>
    /// This class is responsible for gathering data for symbols.
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TickerHistoryController : ControllerBase
    {
        /// <summary>
        /// This function is used to get data for a symbol based on a ticker query and return the returns for an investment.
        /// </summary>
        /// <param name="tickerQuery"></param>
        /// <returns>Return the returns for a given investment.</returns>
        /// <exception cref="Exceptions.InvalidQueryException"></exception>
        // GET api/<TickerHistory>/tickerQuery?fromDate={yyyy-MM-dd}&toDate={yyyy-MM-dd}&tickerSymbol={SYMBOL}'
        [HttpGet("tickerQuery")]
        public async Task<List<double>> TickerData([FromQuery] TickerQuery tickerQuery)
        {
            System.Diagnostics.Debug.WriteLine("HIT");
            if (string.IsNullOrEmpty(tickerQuery.tickerSymbol))
            {
                throw new InvalidQueryException(InvalidQueryException.MISSING_TICKER_SYMBOL_MESSAGE); // Can't perform search without a symbol
            }
            if (string.IsNullOrEmpty(tickerQuery.fromDate.ToString()))
            {
                tickerQuery.fromDate = new DateTime(DateTime.Now.Year, 1, 1);
            }
            // toDate is missing
            if (string.IsNullOrEmpty(tickerQuery.toDate.ToString()))
            {
                tickerQuery.toDate = DateTime.Today;
            }
            // Too long of query
            if ((tickerQuery.toDate - tickerQuery.fromDate).TotalDays > IEX.MAX_QUERY_TIMERANGE * IEX.DAYS_IN_YEAR)
            {
                throw new InvalidQueryException(InvalidQueryException.MAX_TIMERANGE_EXCEEDED_MESSAGE);
            }
            // Start time comes after end
            if ((tickerQuery.toDate - tickerQuery.fromDate).TotalDays < 0)
            {
                throw new InvalidQueryException(InvalidQueryException.INVALID_START_AND_END_DATE_COMBINATION_MESSAGE);
            }

            using (var client = new HttpClient())
            {
                var url = IEX.urlBuilder(tickerQuery); // Creates URL for API call
                client.BaseAddress = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string jsonData = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine(jsonData);
                    List<TickerData> data = JsonSerializer.Deserialize<List<TickerData>>(jsonData); // Map JSON to TickerData list

                    return ReturnCalculator.calculateReturn(data);
                    
                }
                else
                {
                    return null;
                }

            }
        }

    }
}

测试:

using Microsoft.AspNetCore.Mvc.Testing;
using NUnit.Framework;
using RedAeris.Exceptions;

namespace RedAeris.Tests.Controllers
{
    [TestFixture]
    public class TickerHistoryControllerTests
    {

        private WebApplicationFactory<Program> factory;

        [SetUp]
        public void Setup()
        {
            factory = new WebApplicationFactory<Program>();
        }

        [TearDown]
        public void Teardown()
        {
            factory.Dispose();
        }

        [Test]
        public async Task ShouldThrowInvalidQueryExceptionWithNoTicker()
        {

            var client = factory.CreateClient();
            var url = "https://localhost:7267/api/TickerHistory/tickerQuery?fromDate=2023%2F04%2F01&toDate=2023%2F04%2F20";

            // Act & Assert
            Assert.ThrowsAsync<InvalidQueryException>(async () => await client.GetAsync(url));
            // Assert.AreEqual("Response status code does not indicate success: 404 (Not Found).", exception.Message);
        }
    }
}

测试未按预期运行

qfe3c7zg

qfe3c7zg1#

你的url变量应该是:

var url = "/api/TickerHistory/tickerQuery?fromDate=2023%2F04%2F01&toDate=2023%2F04%2F20";

相关问题