I have a test method:
[Fact]
public void Test001()
{
var mock = new Mock<IValidator>();
var sut = new Sut(mock.Object);
try
{
Action a = () => sut.TestedMethod();
a.Should().Throw<ArgumentException>();
}
catch { }
mock.Verify(x => x.IsValid(), Times.Once);
}
and a TestedMethod
:
public void TestedMethod()
{
_ = _validator.IsValid();
throw new ArgumentException();
}
Is there any way to get rid of try-catch here?
However, when eliminating try-catch, naturally, the Verification always fails.
Is there any beautiful workaround?
CodePudding user response:
If you would use xunit's built-in Throws
function (instead of FluentAssertion) then you don't need the try-catch
block.
Simply just:
Assert.Throws<ArgumentException>(() => sut.TestedMethod());
UPDATE #1
The Assert.Throws
does not throw exception. It returns the captured exception to allow further assessment, like this:
var actualException = Assert.Throws<ArgumentException>(() => sut.TestedMethod());
Assert.Equal(expectedErrorMessage, actualExcepion.Message);
Since it does not throw exception the test can continue its execution with the Verify
check