我没有很多经验模拟测试。
我写了一个服务来从属性文件加载代码。这很好用。现在我想为这项服务编写单元测试,但不知何故它不起作用,出了什么问题以及如何修复它?在我的服务类+单元测试类和属性文件下面。
public class PhoneCodeService {
private static final Logger LOG = LoggerFactory.getLogger(PhoneCodeService.class);
private static final String PROPERTY_FILE_NAME = "phone-code.properties";
private final Map<String, String> phoneCodes;
private final Properties properties = new Properties();
/**
* Default constructor
*/
public PhoneCodeService() {
try {
readPhoneCodesFromPropertyFile();
} catch (IOException e) {
LOG.debug("Could not read property file " + PROPERTY_FILE_NAME);
}
Map<String, String> map = new HashMap<String, String>();
for (String key : properties.stringPropertyNames()) {
map.put(key, properties.getProperty(key));
}
phoneCodes = map;
}
public String getPhonecode(final String input) {
String code = phoneCodes.get(input);
return code;
}
private void readPhoneCodesFromPropertyFile() throws IOException {
InputStream inputStream = null;
try {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTY_FILE_NAME);
if (inputStream == null) {
throw new FileNotFoundException("property file is missing");
}
properties.load(inputStream);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
单元测试类
public class PhoneCodeServiceTest {
@Mock
private PhoneCodeService phoneCodeService;
@Before
public void setUp() {
initMocks(this);
when(phoneCodeService.getPhonecode("86101")).thenReturn("984");
}
@Test
public void testNull() {
assertEquals(null, phoneCodeService.getPhonecode(null));
}
@Test
public void testCodes() {
final String[] CODES = {"86101"};
for (String code : CODES) {
assertEquals("984", phoneCodeService.getPhonecode(code));
}
}
}
我的属性文件示例
000=1
001=2
002=3
003=4
004=5
答案 0 :(得分:0)
我有点惊讶。从您的代码中,您感觉更像是在测试Mock框架而不是代码。您的代码中没有任何内容被执行
在这种情况下,更传统的测试方法会更有益。
创建一个名为phone-code.properties的测试资源文件,其中包含测试值 在测试期间,此文件必须在类路径中可用
在不模仿的情况下测试PhoneCodeService
然后测试如下:
public class PhoneCodeServiceTest {
@Test
public void testNull() {
PhoneCodeService phoneCodeService = new PhoneCodeService();
assertEquals(null, phoneCodeService.getPhonecode(null));
}
@Test
public void testCodes() {
PhoneCodeService phoneCodeService = new PhoneCodeService();
final String[] CODES = {"86101"};
for (String code : CODES) {
assertEquals("984", phoneCodeService.getPhonecode(code));
}
}
对于100%的代码覆盖率,您的类需要一种向PhoneCodeService提供非现有文件的方法