I dont have alot of experience mock testing.
I wrote a service to load codes from a property file. This works fine. Now I would like to write unit tests for this service, but somehow it is not working, what is wrong and how to fix it? below my service class + unit test class and property file.
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);
}
}
}
Unit test class
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));
}
}
}
Example of my property file
000=1
001=2
002=3
003=4
004=5