【发布时间】:2015-02-21 13:34:55
【问题描述】:
通常,一个 Java 类有多个我们想用 JUnit 测试的公共方法。当我们可以使用参数化技术这两种公共方法时会发生什么?
我们是否应该为要使用参数化参数测试的每个公共方法保留一个 JUnit 测试类,或者我们如何将两者都保留在一个 JUnit 测试类中?
用于测试公共方法 RegionUtils.translateGeographicalCity(...) 的示例参数化 JUnit 测试类
@RunWith(Parameterized.class)
public class RegionUtilsTest {
private String geographicalCity;
private String expectedAwsRegionCode;
public RegionUtilsTest(final String geographicalCity,
final String expectedAwsRegionCode) {
this.geographicalCity = geographicalCity;
this.expectedAwsRegionCode = expectedAwsRegionCode;
}
@Parameters(name = "translateGeographicalCity({0}) should return {1}")
public static Collection geographicalCityToAwsRegionCodeMapping() {
// geographical city, aws region code
return Arrays.asList(new Object[][] { { "Tokyo", "ap-northeast-1" },
{ "Sydney", "ap-southeast-2" },
{ "North Virginia", "us-east-1" }, { "Oregan", "us-west-2" },
{ "N.California", "us-west-1" }, { "Ireland", "eu-west-1" },
{ "Frankfurt", "eu-central-1" }, { "Sao Paulo", "sa-east-1" },
{ "Singapore", "ap-southeast-1" } });
}
@Test
public void translateGeographicalCityShouldTranslateToTheCorrectAwsRegionCode() {
assertThat(
"The AWS Region Code is incorrectly mapped.",
expectedAwsRegionCode,
equalTo(RegionUtils.translateGeographicalCity(geographicalCity)));
}
@Test(expected = NamedSystemException.class)
public void translateGeographicalCityShouldThroughAnExceptionIfTheGeographicalCityIsUnknown() {
final String randomGeographicalCity = RandomStringUtils
.randomAlphabetic(10);
RegionUtils.translateGeographicalCity(randomGeographicalCity);
}
}
【问题讨论】:
标签: java junit parameterized