【问题标题】:Best Practice for multiple Parameterized JUnit Tests多个参数化 JUnit 测试的最佳实践
【发布时间】: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


    【解决方案1】:

    布局:记住你不做'类测试',你做'单元测试'。以有意义的方式组织和命名您的测试,这不会让任何未来的代码读者感到惊讶。通常这意味着在一个测试类中测试所有简单的方法,每个方法使用一到两个参数化测试。但有时一种方法很复杂,需要更详细的测试,然后为它创建一个专用的测试文件可能是个好主意

    工具:您需要某种数据提供者。那么通常每个测试都有自己的数据提供者。有时多个方法可以共享同一个数据提供者。可悲的是,JUnit 在那个领域很烂。最近出现了一些扩展 JUnit 的库。 JUnit 本身也在添加@Parameterized、@Theories 等,但仍然 - 它很糟糕。所以如果你不能切换到 TestNG 或 Spock 试试这些:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多