【发布时间】:2014-11-20 10:29:14
【问题描述】:
我目前正在尝试重构一些单元测试,因为它们包含太多的硬编码数据。 类结构如下:
public class BaseClassValidator {
[Test]
public void TestAddress(){
Address a = GetAddress();
if (a != null){
// verify and validate here
Assert.AreEqual(..., ...);
}
}
[Test]
public void TestPhone(){
// almost the same as above, with GetPhone();
}
// ... other public methods here ...
protected Address GetAddress(){
return null;
}
protected Phone GetPhone(){
return null;
}
}
public class US: BaseClassValidator{
protected override Address GetAddress(){
Address address = new Address();
address.FirstName = "firstname";
// fill in the address data ...
return address;
}
// override GetPhone as well and other protected methods
}
以及许多其他用于相同目的的类 - 验证国家/地区地址是否有效。 每个子类都必须重写获取测试数据的方法,正如您可以想象的那样,这使得文件越来越大,输入数据在我看来可以以不同的方式获取/设置。此外,其中一些子类定义了特定的测试成员来检查地址是否有效,有几个检查,例如:
public class US: BaseClassValidator {
// override the method GetAddress, as explained above ...
// define a new test method here...
[Test]
public void TestValidator {
Address a = GetAddress();
a.State = "KS";
// validate the address
// and assert that we get an error because state is wrong
Address a = GetAddress();
a.street = "";
// validate and assert that we get an error because street is wrong
// and so on...
}
}
我想知道是否有更好的方法来做到这一点,因为我们似乎在部分使用基类来测试一些数据,但对于更具体的事情,我们正在使用子类 - 这可能是有道理的,但是那么似乎我们失去了使用上述模板模式的好处。我不喜欢创建数据的方式,因为使用不同的方法,例如使用数据驱动测试,我们可以从文件(例如 xml)中读取测试数据。
有没有更好的方法在测试之间共享数据? 遇到这种情况怎么处理?
【问题讨论】:
标签: c# unit-testing nunit xunit data-driven-tests