【发布时间】:2018-08-13 10:11:37
【问题描述】:
我在我的 .NET Core 应用程序中实现了一项服务,我调用它来验证我的模型。不幸的是,如果服务(不是我的)无效,服务(不是我的)会抛出异常,如果它是有效的(因为它是一个 void 方法),它只会以 200 OK 响应。
所以基本上我会这样做:
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。
我应该如何使用 NSubstitute 来模拟它?
【问题讨论】:
-
@mjwills 这只是为了展示我如何处理我找到的服务的响应。由于如果模型无效,服务会抛出异常,因此我必须像这样处理“响应”/验证。
-
@mjwills 没有必要,因为不可能实现这个服务作为示例。我的帖子完美地解释了我的问题。
标签: c# unit-testing .net-core nsubstitute