Often, a Java class has more than one public method that we want to test with JUnit. What happens when both public methods are something we can use Parameterized techniques?
Should we keep a JUnit Test class for each public method we want to test with Parameterized parameters, or how do we keep both in one JUnit Test class?
Sample Parameterized JUnit Test class for testing the public method RegionUtils.translateGeographicalCity(...)
@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);
}
}