首页 > 解决方案 > XUnit 对以接口作为返回类型的方法进行单元测试

问题描述

我的服务类中有一个名为ClassifyImage. 而这个方法的返回类型是一个接口。

public interface ICreatePrediction
{
     Task<IMLResponseObject> ClassifyImage(IFormFile file, int age, string sex, string location, string imageId);
} 

我想在我的测试类中调用这个方法并定义一个结果。我曾经A.CallTo这样做过。

public class GetClassificationHandlerTests
{
    //rest of the code

    private readonly Mock<IMLResponseObject> _customResponse;

    public GetClassificationHandlerTests(ITestOutputHelper testOutputHelper)
    {
        //rest of the code

        _customResponse = new Mock<IMLResponseObject>();
    }

    [Fact]
    public async Task Image_Scan_With_All_InterfaceResponses_Successful_Returns_Valid_Output()
    {
         A.CallTo(() => _iCreatePrediction.ClassifyImage(_customInput.file, _customInput.age, _customInput.sex, _customInput.location, _customInput.imageId))
                .Returns(_customResponse);
         
        //The result should be of the type IMLResponseObject
        result.ShouldBeOfType<IMLResponseObject>();

         //rest of the code
     }
}

请注意,_customInput在代码中定义。

首先,我需要知道这是正确的方法吗?

然后,在上面的代码中,我收到一条错误消息 'IReturnValueArgumentValidationConfiguration<Task<IMLResponseObject>>' does not contain a definition for 'Returns' and the best extension method overload 'ValueTaskReturnValueConfigurationExtensions.Returns<Mock<IMLResponseObject>>

它来自生产线A.CallTo(() => _iCreatePrediction.ClassifyImage.....

对此问题的任何帮助或提示都将受到高度赞赏。

标签: c#asp.netxunitxunit.net

解决方案


推荐阅读