I'm using C# with nUnit to unit test my project and I'm trying to write some unit tests that ensure a certain Exception is called but my tests keep failing. After a lot of testing to work out the issue, I managed to identify the cause of it and created a small code example that shows my issuew below.
My unit test code:
[Test]
public void TestExceptionIsRaised()
{
var ex = Assert.Throws<UnauthorizedAccessException>(() => TestExceptionMethod());
StringAssert.Contains("Attempted to perform an unauthorized operation", ex.Message);
}
My method with no error checking:
public void TestExceptionMethod()
{
throw new UnauthorizedAccessException();
}
Now if I run that unit test with the above method... it throws the exception, nUnit detects it and the test passes. However, this code is a problem because it has no error handling and will crash if I release it like this.
So to solve that problem, I add some error handling into my method like this:
public void TestExceptionMethod()
{
try
{
throw new UnauthorizedAccessException();
}
catch (UnauthorizedAccessException ex)
{
// Do something about the error
}
}
But now when I run the unit test it fails with this error:
Expected: System.UnauthorizedAccessException But was: null
So rather than having to choose between a unit test or proper error handling, I tried to re-throw the error like this:
public void TestExceptionMethod()
{
try
{
throw new UnauthorizedAccessException();
}
catch (UnauthorizedAccessException ex)
{
// Do something about the error
throw;
}
}
Finally, everything now works. The unit test passes every time. And my method can still catch the error and do something about it.
However from what I've heard it isn't good practice to keep re-throwing errors like this??? So I'm just wondering is my solution "correct"? Or is there a better way of unit testing for an exception without having to remove the try/catch blocks from the original method?
Aucun commentaire:
Enregistrer un commentaire