如果使用 NSubstitute 出现问题,则模拟抛出异常的方法

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.

我该如何使用 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);
}