我在尝试使用 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/