开发者

How to write Nunit TestCases to test the correct List of strings is returned

I have a method like:

public virtual IList<string> Validate()
{
   ...
}

I want to unit test this using NUnit. This is part of a class Vehicle.

A Vehicle can be of different types ie. Car Boat Truck etc.

At the top of my TestFixture I set up the VehicleTypes:

private VehicleType[] _vehicleTypes;

[SetUp]
public void MyTestInitialize()
{
    transScope = new TransactionScope();

    var boat= new VehicleType { Name = "boat" };
    var car = new VehicleType { Name = "car" };
    var truck = new VehicleType { Name = "truck" };

    _vehicleTypes= new VehicleType[] { boat, car, truck };

    ...
}

What I want is to test that an error message is sent back from the method for the boat only.

My unit test is as follows:

[TestCase(0, "This vehicle is inappropriate because it doesn't have wheels")]
[TestCase(1, null)]
[TestCase(2, null)]
public void Validate_Vehicle_ReturnsAppropriateErrorMessage(int vehicleType, string expectedResult)
{
   var vehicle = new Vehicle { VehicleType = _vehicleTypes[vehicleType] };

   var results = vehicle.Validate();

   string result;

   if (results.Count == 0)
      result = null;
   else
      result = results[0];

   Assert.IsTrue(expectedResult == result);
}

So this was how I was trying to test it using Te开发者_如何学编程stCases. However I'm not sure this is the right approach as unit tests shouldn't contain ifs?

Also maybe this is a weird approach to writing a test for different types?

Anyone have any better suggestions?


I would break these up into multiple tests. By doing so you can write one that test the normal behavior (non boat) as well as the boat. If any of these test fail in the future, you won't have to try and figure out what iteration of the data driven tests failed. The test will speak for itself.

In this case I would write one for the behavior for the boat and one for the non boat. The other iterations aren't interesting (and likly use the same code path this test is validating as the other non boats)

public void Validate_VehicleIsBoat_ReturnsAppropriateErrorMessage()
{   
   string expectedResult = "This vehicle is inappropriate because it doesn't have wheels";
   var vehicle = new Vehicle { VehicleType = VehicleType.Boat };  //or whatever it is in your enum

   var results = vehicle.Validate();   

   Assert.AreEqual( expectedResult, results[0] );
}

public void Validate_VehicleIsNotBoat_DoesNotReturnErrorMessage()
{   
   var vehicle = new Vehicle { VehicleType = VehicleType.Car };  //or whatever it is in your enum

   var results = vehicle.Validate();   

   Assert.IsNull( results ); // or whatever the no error message case is. Will results[0] have an empty string?
}

You could add additional tests to validate the result sets have all the data you want as well.

Anyway, hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜