I'm having trouble testing my custom Exception with NUnit. For context, I'm building a simple airport program to improve C#, which I started learning recently. Planes can't land in the airport if it's stormy or if the airport is full. Extracts of the relevant code:
Extract from Airport class with Exceptions:
public void Land(Plane plane)
{
try
{
if (weather.Forecast() == "stormy")
{
throw new StormyException("It's too stormy to land");
}
if (planes.Count >= _Capacity)
{
throw new CapacityException("Airport is full");
}
planes.Add(plane);
Console.WriteLine($"{ plane.Name } has landed at {_AirportName}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Example of the Exceptions themselves:
class StormyException : Exception
{
public StormyException(string message)
: base(String.Format(message))
{
}
}
Example of a failing test:
[Test]
public void PlaneWontLandIfStormy()
{
var weather = new Mock<Weather>();
weather.Setup(x => x.Forecast()).Returns("stormy");
var airport = new Airport("TestAirport", weather.Object, 10);
var exception = Assert.Throws<Exception>(() => airport.Land(plane));
Assert.AreEqual(exception.Message, "It's too stormy to land");
}
When I run the program, everything works fine. However this test does not pass, with this error: Expected: <System.Exception> But was: null
. I have looked into this and seen syntax along the lines of [ExpectedException]
... but I cannot seem to solve the problem. I'm very new to C# so any help would be much appreciated, thank you!
Your Land
method need to throw the exception, not catch it.
public void Land(Plane plane)
{
if (weather.Forecast() == "stormy")
{
throw new StormyException("It's too stormy to land");
}
if (planes.Count >= _Capacity)
{
throw new CapacityException("Airport is full");
}
planes.Add(plane);
Console.WriteLine($"{ plane.Name } has landed at {_AirportName}");
}
in your test
var exception = Assert.Throws< StormyException >(() => airport.Land(plane)); Assert.AreEqual(exception.Message, "It's too stormy to land");
or
var exception = Assert.Throws< StormyException >(() => airport.Land(plane)); exception.Message.Equals("It's too stormy to land");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.