I'm currently in the process of working through a Unit Testing in C# course - specifically for NUnit (I'm using NUnit 3.8.1 with NUnit3TestAdapter 3.1.13).
My issue in question, is that when I'm testing for an exception to be thrown, my debugger stops & throws an exception on the method that I'm testing. I'm not sure if I'm mistaken with the behaviour, but I can't see what I've done wrong.
Firstly - I've read up on the documentation & can't see a problem.
I've also looked through various other posts on stack overflow that just don't seem to quite point at the answer, as none of these solutions have worked for me.
Is there some Assert method which can be used for unit test on whether a method throws an exception?
C# Unit Testing - Test method throwing NullReferenceException
The class I'm testing is as follows (and was provided from the instructor on the course - they have demonstrated that this works).
using System;
namespace TestNinja.Fundamentals
{
public class ErrorLogger
{
public string LastError { get; set; }
public event EventHandler<Guid> ErrorLogged;
public void Log(string error)
{
if (String.IsNullOrWhiteSpace(error))
throw new ArgumentNullException();
LastError = error;
// Write the log to a storage
// ...
ErrorLogged?.Invoke(this, Guid.NewGuid());
}
}
}
And finally, my test methods -
using NUnit.Framework;
using TestNinja.Fundamentals;
namespace TestNinja.UnitTests
{
[TestFixture]
public class ErrorLoggerTests
{
//private ErrorLogger _errorLogger;
[SetUp]
public void SetUp()
{
//_errorLogger = new ErrorLogger();
}
[Test]
public void Log_WhenCalled_SetTheLastErrorProperty()
{
var logger = new ErrorLogger();
logger.Log("a");
Assert.That(logger.LastError, Is.EqualTo("a"));
}
[Test]
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void Log_InvalidError_ThrowArgumentNullException(string error)
{
var logger = new ErrorLogger();
Assert.That(() => logger.Log(error), Throws.ArgumentNullException);
}
}
}
The test I'm talking about is Log_InvalidError_ThrowArgumentNullException
. On each test case the code breaks on the line throw new ArgumentNullException();
in ErrorLogger
. I have to close the box & continue running the code.
When I run this test individually, the test runs to completion, however when I run all, that's where the exception is thrown & my testing is stopped.
Originally, my unit testing had the SetUp
method uncommented & I was using that private field, however I swapped over to a fresh instance to make sure there weren't any issues with lingering objects.