我正在爲某些用戶數據實現驗證器。如何避免重複的JUnit測試
不幸的是,用戶數據總共包含37個字段,這使得測試類相當怪異。
大多數字段包含具有相似要求的數據(即檢查長度限制)。
摘錄代碼:
public class Userdata {
private String firstName;
private String lastName;
private String birthName;
private String birthPlace;
private String city;
private String street;
private String zipCode;
private String country;
private String citizenship;
// getters/setters
}
和(部分)測試類:
public class UserdataValidatorTest {
UserdataValidator cut = new UserdataValidator();
@Test
public void firstNameMaxPermittedLength()
{
Userdata userdata = minimumRequirements();
userdata.setFirstName(utf8Chars(64));
assertNoViolations(cut.validate(userdata));
}
@Test
public void firstNameExceedsPermittedLength()
{
Userdata userdata = minimumRequirements();
userdata.setFirstName(utf8Chars(65));
assertSingleViolation(cut.validate(userdata));
}
@Test
public void lastNameMaxPermittedLength()
{
Userdata userdata = minimumRequirements();
userdata.setLastName(utf8Chars(64));
assertNoViolations(cut.validate(userdata));
}
@Test
public void lastNameExceedsPermittedLength()
{
Userdata userdata = minimumRequirements();
userdata.setLastName(utf8Chars(65));
assertSingleViolation(cut.validate(userdata));
}
@Test
public void citizenshipIllegalChars()
{
Userdata userdata = minimumRequirements();
userdata.setCitizenship("2E");
assertSingleViolation(cut.validate(userdata));
}
@Test
public void citizenshipLegal()
{
Userdata userdata = minimumRequirements();
userdata.setCitizenship(iso3166Country());
assertNoViolations(cut.validate(userdata));
}
@Test
public void citizenshipTooLong()
{
Userdata userdata = minimumRequirements();
userdata.setCitizenship(alphabetic(3));
assertSingleViolation(cut.validate(userdata));
}
@Test
public void citizenshipTooShort()
{
Userdata userdata = minimumRequirements();
userdata.setCitizenship(alphabetic(1));
assertSingleViolation(cut.validate(userdata));
}
@Test
public void countryIllegalChars()
{
Userdata userdata = minimumRequirements();
userdata.setCountry("2E");
assertSingleViolation(cut.validate(userdata));
}
@Test
public void countryLegal()
{
Userdata userdata = minimumRequirements();
userdata.setCountry(iso3166Country());
assertNoViolations(cut.validate(userdata));
}
@Test
public void countryTooLong()
{
Userdata userdata = minimumRequirements();
userdata.setCountry(alphabetic(3));
assertSingleViolation(cut.validate(userdata));
}
@Test
public void countryTooShort()
{
Userdata userdata = minimumRequirements();
userdata.setCountry(alphabetic(1));
assertSingleViolation(cut.validate(userdata));
}
// ... more tests
}
有沒有生成測試用例一個愉快的方式?我仍然想爲每個國家進行4次測試。
編輯
有許多複雜的(互相依賴)領域,這是我在這裏省略,這是一個原因,我決定不使用Bean驗證API。
那麼在這些驗證器的循環中拋出很多隨機數據(使用常量種子;請參閱Random(int seed))?生成的數據+循環=不那麼詳細。 – tucuxi
另請參閱http://stackoverflow.com/questions/6453235/what-does-damp-not-dry-mean-when-talking-about-unit-tests – Raedwald