0

I'm using NSubsitute to mock a class that my method under test uses. I want to ensure that my method does not throw exceptions that are caused by its dependencies.

Is there a way to force a mocks to throw an exception, no matter which of its methods are called?

I know, I can 'prepare' the mock to throw an exception if a specific method will be called. But then I also need to check if this prepared method was called at all, to prevent others to change the code without changing the unit test. But this would also mean to start testing the algorithm which I don't want to do.

Edit: Because I'm trying to mock the IRestClient from RestSharp I found at least a way to throw exceptions for every call that will return a Task<IRestResponse> - this is sufficient for my use case. Maybe my question wasn't specific enough and did imply to much of a wrong solution.

        var restClient = Substitute.For<IRestClient>();
        restClient.ReturnsForAll<Task<IRestResponse>>(t => throw new Exception("something did go wrong with the web api call"));
al-bex
  • 666
  • 1
  • 9
  • 24
  • _"Is there a way to force a mocks to throw an exception, no matter which of its methods are called?"_ - [the docs on exceptions](https://nsubstitute.github.io/help/throwing-exceptions/) say that _"Callbacks can be used to throw exceptions **when a member is called.**_ so it doesn't sound like it. – stuartd Apr 16 '19 at 15:58
  • 1
    This isn't supported by NSubstitute. It might be easier to manually create a test double for this. If you're using VS it can [generate a sub-type that defaults to all members throwing `NotImplementedException`](https://learn.microsoft.com/en-us/visualstudio/ide/reference/implement-abstract-class?view=vs-2019). – David Tchepak Apr 16 '19 at 23:14
  • 1
    Isn't it an option to pass `null` as the service instead of mocking it? This way any method call will throw an exception. – Mihai Apr 17 '19 at 14:10
  • this is for sure a nice hack ;-) – al-bex Apr 18 '19 at 07:50
  • @DavidTchepak you should write your comment as an answer so I can accept and close this – al-bex Apr 18 '19 at 07:52

1 Answers1

1

This isn't supported by NSubstitute.

It might be easier to manually create a test double for this. If you're using VS it can generate a sub-type that defaults to all members throwing NotImplementedException. (R# and Rider provide similar options.)

David Tchepak
  • 9,826
  • 2
  • 56
  • 68