0

我有一个带有 2 个服务接口的控制器类:一个是外部 URL 的 post 方法,第二个是本地存储库。在控制器测试类中,我只想moq interface1,而不是第二个。我怎样才能做到这一点?或者测试这个控制器的最佳方法是什么?

[Route("api/MyAPI")]
    [ApiController]
    public class MyAPIController : Controller
    {
        private readonly Interface1 _interface1;
        private readonly Interface2 _interface2;

        public ProfitLossGrowthRateController(Interface1 interface1,
            Interface2 interface2)
        {
            _interface1= interface1;
            _interface2 = interface2;
        }

        [HttpPost("CodeAPI")]
        [Produces(MediaTypeNames.Application.Json)]
        [ProducesResponseType(typeof(List<Response>), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(Error), StatusCodes.Status400BadRequest)]
        [ProducesResponseType(typeof(Error), StatusCodes.Status500InternalServerError)]
        public async Task<List<Response>> GetCodeAPIController
            (Request request)
        {
            var response1 = await _interface1.GetCodesByFilter(request);
            return await _interface2.GetGrowthRate(response1.Codes);
        }

    }

同时,在这个控制器的第一个版本中,当我没有第一个接口时,我这样编写控制器测试并且它可以正常工作:

public class MyAPIControllerTest : IntegrationBaseTest
    {
        public MyAPIControllerTest ()
            : base(nameof(Repository))
        {
            DataProvider.InsertData<Data1>
                (Context, nameof(Data1));
        }


        [Theory]
        [InlineData("/api/MyAPI/CodeAPI")]
        public async Task GetGrowthRate(string url)
        {
            var request = new Request()
            {
                Filter = new List<string>() { "111" }
            };
            var content = await HttpHandler.PostURI<Request>(url, request, Factory);
            List<Response> response = JsonConvert.DeserializeObject<List<Response>>(content);

            // Assert
            Assert.NotNull(response);
            Assert.Single(response);
            Assert.Equal("111", response[0].CompanyNationalCode);
        }
   }
4

0 回答 0