-
I'm trying to find an elegant solution for my current problem, but I'm probably approaching this incorrectly. Maybe one of you has a good idea how to improve this? Here's my code: public class OAuthServiceTests
{
[Theory]
[MemberData(nameof(InvalidProcessAccessTokenInput))]
public async Task ProcessAccessTokenInput_should_throw_exception_for_invalid_input(TokenController.AccessTokenInput input, Type expectedException)
{
// Arrange
var oAuthService = new OAuthService(null);
// Act
Func<Task> act = () => oAuthService.ProcessAccessTokenInput(input, string.Empty, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<expectedException>();
}
public static TheoryData<TokenController.AccessTokenInput, Type> InvalidProcessAccessTokenInput =>
new()
{
{ new TokenController.AccessTokenInput { GrantType = "wrong" }, typeof(UnsupportedGrantTypeException) },
{ new TokenController.AccessTokenInput { }, typeof(InvalidInputException) }
};
} Of course this doesn't compile. I didn't find a method in FluentAssertions that I could use instead. But I hope from the example it's clear what I want to achieve. In short: I want to pass the expected exception type in the Theory, and then do the assertion with FluentAssertions. I searched, but it seems that this is not expected/recommended behavior. Do I have to write a switch statement for each exception type instead? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You're so close! In our test suite we use have this test using a generic test and non-generic memberdata. I just checked and you should be able to use [Theory]
[MemberData(nameof(InvalidProcessAccessTokenInput))]
public async Task ProcessAccessTokenInput_should_throw_exception_for_invalid_input<T>(TokenController.AccessTokenInput input, T _)
where T : Exception
{
// Arrange
var oAuthService = new OAuthService(null);
// Act
Func<Task> act = () => oAuthService.ProcessAccessTokenInput(input, string.Empty, CancellationToken.None);
// Assert
await act.Should().ThrowAsync<T>();
}
public static TheoryData<TokenController.AccessTokenInput, Exception> InvalidProcessAccessTokenInput => new()
{
{ new TokenController.AccessTokenInput { GrantType = "wrong" }, new UnsupportedGrantTypeException() },
{ new TokenController.AccessTokenInput { }, new InvalidInputException() }
}; |
Beta Was this translation helpful? Give feedback.
You're so close!
In our test suite we use have this test using a generic test and non-generic memberdata.
fluentassertions/Tests/FluentAssertions.Specs/Exceptions/ExceptionAssertionSpecs.cs
Lines 31 to 38 in 17c52d0
I just checked and you should be able to use