重构Java类以进行无状态单元测试

时间:2018-12-17 02:26:58

标签: java junit mocking

我正在尝试为Java类编写单元测试。我目前有一个Java类,看起来类似于以下内容:

public class MyClass {
    private Map<String, String> allowedCountries;

    public MyClass() {
        loadMetadata();
    }

    private void loadMetadata() {
        // my actual code loads this information from
        // a SQL database
        allowedCountries = new HashMap<>();
        allowedCountries.put("US", "United States");
        allowedCountries.put("SG", "Singapore");
        allowedCountries.put("DE", "Germany");
    }

    public boolean checkCountry(String code) {
        return allowedCountries.containsKey(code);
    }
}

MyClass clazz = mock(MyClass.class);
when(clazz.checkCountry("DE")).thenReturn(true);
when(clazz.checkCountry("JP")).thenReturn(false);
assertTrue(clazz.checkCountry("DE"));
assertFalse(clazz.checkCountry("JP"));

单元测试将通过MyClass类,尤其是checkCountry()方法。但是问题在于上面的代码不允许我们轻松地模拟已知国家的地图。 我知道,单元测试理想上应该是无状态的。有什么方法可以重构此代码,以便也可以模拟已知国家/地区的地图?

0 个答案:

没有答案