c# - 当参数为 MultipartFormDataStreamProvider 时无法模拟接口(interface)方法

标签 c# .net unit-testing moq

我在尝试使用 MockedClass.Setup(x => x.Method()) 模拟接口(interface)时遇到了这个奇怪的问题。

这是我正在模拟的界面。

public interface IClassFactory
{
    object GetValueFromFormData(string key, MultipartFormDataStreamProvider provider);
}

这是我的测试。

    [TestMethod]
    [ExpectedException(typeof(NullReferenceException))]
    public async Task ClassApiController_ImportClassList_ThrowsNullReferenceExceptionWhenNoClassId()
    {
        // Arrange
        _classFactory = new Mock<IClassFactory>();

        // THIS IS THE LINE THAT GIVES AN EXCEPTION
        _classFactory.Setup(x => x.GetValueFromFormData("classIdNull", null)).Returns(string.Empty);
        ClassApiController controller = new ClassApiController(_classRepository.Object, _surveyRepository.Object, _classFactory.Object);

        // Act
        string result = await controller.ImportClassList();
    }

如果您查看我的评论“这是给出异常的行”,您会看到我发送了 null,但如果我将 MultipartFormDataStreamProvider 作为实例化类发送也没关系,我仍然得到相同的异常。

Exception message: System.ArgumentException: Expression of type 'System.Net.Http.MultipartFormDataStreamProvider' cannot be used for parameter of type 'System.Net.Http.MultipartFormDataStreamProvider' of method 'System.Object GetValueFromFormData(System.String, System.Net.Http.MultipartFormDataStreamProvider)'

如果你知道为什么我不能仅仅因为它有这个对象作为参数就模拟这个方法,请帮助我,我很无能。

谢谢!

编辑: 在我的答案中查看解决方案

最佳答案

你应该试试

        _classFactory = Mock.Of<IClassFactory>();

        Mock.Get(_classFactory).Setup(x => x.GetValueFromFormData("classIdNull", It.IsAny<MultipartStreamProvider>()))
                     .Returns(string.Empty);

关于c# - 当参数为 MultipartFormDataStreamProvider 时无法模拟接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374147/

相关文章:

c# - 在文本文件中找到字符串后保存整数值

c# - 设置最小起订量并验证是否调用了方法

Python:对类使用文档测试

Python模拟类实例变量

c# - 如何使用一个 xml 文件中的信息在 C# 中创建另一个文件?

c# - 如何将 C# 控制台输出流式传输到 ASP 网页文本框

.net - 我在哪里可以找到 System.Windows.Interactivity 作为可再分发?

.net - 限制 Windows .NET 服务的 CPU 使用率

javascript - 测试 Express 中间件

c# - 如何使用 System.IO.Pipelines 包创建响应 TCP 监听器?