[英]Mocking, with NSubstitute, entity framework FirstOrDefualtAscync method throws exception
[英]Mocking a method that throws exception if something went wrong using NSubstitute
我已经在.NET Core应用程序中实现了一项服务,调用该服务来验证我的模型。 不幸的是,服务(不是我的)如果无效则抛出异常,如果有效则简单地以200 OK响应(因为它是void方法)。
所以基本上我做这样的事情:
try {
await _service.ValidateAsync(model);
return true;
} catch(Exception e) {
return false;
}
我试图模拟ValidateAsync
内的方法,该方法将请求发送到我实现的服务。 ValidateAsync
仅将控制器的输入从前端的某些内容转换为Validate
方法可以理解的内容。
但是,我无法真正看到应如何测试。 这是我尝试过的方法,但对我来说真的没有任何意义。
[TestMethod]
public void InvalidTest() {
var model = new Model(); // obviously filled out with what my method accepts
_theService.Validate(model)
.When(x => { }) //when anything
.Do(throw new Exception("didn't work")); //throw an exception
//Assert should go here.. but what should it validate?
}
基本上When this is called -> throw an exception
这样: When this is called -> throw an exception
。
我应该如何使用NSubstitute模拟它?
根据目前的解释,假设类似于
public class mySubjectClass {
private ISomeService service;
public mySubjectClass(ISomeService service) {
this.service = service;
}
public async Task<bool> SomeMethod(Model model) {
try {
await service.ValidateAsync(model);
return true;
} catch(Exception e) {
return false;
}
}
}
为了覆盖SomeMethod
的错误路径,依赖项在调用时需要引发异常,以便可以按预期执行测试。
[TestMethod]
public async Task SomeMethod_Should_Return_False_For_Invalid_Model() {
//Arrange
var model = new Model() {
// obviously filled out with what my method accepts
};
var theService = Substitute.For<ISomeService>();
theService
.When(_ => _.ValidateAsync(Arg.Any<Model>()))
.Throw(new Exception("didn't work"));
var subject = new mySubjectClass(theService);
var expected = false;
//Act
var actual = await subject.SomeMethod(model);
//Assert
Assert.AreEqual(expected, actual);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.