简体   繁体   中英

Mocking a method that throws exception if something went wrong using NSubstitute

I have implemented a service in my .NET Core application, that I call to validate my model. Unfortunately, the service (not mine) throws an exception if it's invalid and simply responds with a 200 OK if it's valid (since it's a void method).

So basically I do something like this:

try {
    await _service.ValidateAsync(model);
    return true;
} catch(Exception e) {
    return false;
}

I am trying to mock the method inside of ValidateAsync , that sends the request to the service I implemented. ValidateAsync only converts my controller's input from something on my frontend, to something the Validate method understands.

However, I am unable to really see how I am supposed to test this. Here's what I have tried, but it doesn't really make any sense to me.

[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?
}

So basically: When this is called -> throw an exception .

How am I supposed to mock that using NSubstitute?

Based on current explanation the assumption is something like

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;
        }
    }

}

In order to cover a false path for SomeMethod , the dependency needs to throw an exception when invoked so that the test can be exercised as expected.

[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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM