【问题标题】:How to write Nunit TestCases to test the correct List of strings is returned如何编写 Nunit TestCases 来测试返回的字符串列表是否正确
【发布时间】:2011-08-02 00:49:01
【问题描述】:

我有一个类似的方法:

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

我想使用 NUnit 对此进行单元测试。这是 Vehicle 类的一部分。

Vehicle 可以是不同的类型,即。 CarBoatTruck

在我的TestFixture顶部我设置了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 };

    ...
}

我想要测试的是仅从船的方法发回错误消息。

我的单元测试如下:

[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);
}

这就是我尝试使用 TestCases 对其进行测试的方式。但是我不确定这是正确的方法,因为单元测试不应该包含ifs

也许这是为不同类型编写测试的一种奇怪方法?

谁有更好的建议?

【问题讨论】:

    标签: asp.net-mvc unit-testing nunit


    【解决方案1】:

    我会将这些分成多个测试。通过这样做,您可以编写一个测试正常行为(非船)以及船。如果将来这些测试中的任何一个失败,您将不必尝试找出数据驱动测试的迭代失败。测试会自己说话。

    在这种情况下,我会为船的行为写一个,为非船写一个。其他迭代并不有趣(并且可能使用与其他非船相同的代码路径,该测试正在验证)

    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?
    }
    

    您可以添加额外的测试来验证结果集是否也包含您想要的所有数据。

    无论如何,希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-15
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多