I would like to write one unit test for a set of different exception types. My common approach is to use InlineAutoMoqData for a certain set of test inputs. This works fine for values but I cannot get it working for types.
Below you can find my idea / wished solution:
[Theory]
[InlineAutoMockData(typeOf(HttpRequestException)]
[InlineAutoMockData(typeOf(InvalidOperationException)]
public async void MyTestFunction_Should_HandleExceptions(Type exceptionType, Mock<HttpClient> clientMock)
{
// Arrange
var cut = CreateCut();
clientMock.Setup(c => c.SendAsync()).ThrowsAsync(new Exception()); // here I want to create a generic Exception dependend on the exceptionType instead of "new Exception"
// Act
var result = cut.DoSomething();
// Assert
result.Should().BeTrue();
}
I could add a switch case checking "exceptionType" and moq the client dependend on it. This solution works but does not feel "right". I think there has to be a more elegant solution to it.
You can use the Activator
to create an object from a type.
clientMock.Setup(c =>
c.SendAsync()).ThrowsAsync((Exception) Activator.CreateInstance(exceptionType));