I have test cases that require to mock HashMap class but it appears that JMockit encounters difficulties when mocking it. The following code trigger a NPE in the Expectations block :
public class TestKO {
public class ClassUnderTest {
private final Map<String, String> dependency;
public ClassUnderTest() {
this.dependency = new HashMap<String, String>();
}
public void register(final String key, final String value) {
dependency.put(key, value);
}
}
@Test
public void ko(@Mocked("put") final HashMap<String, String> dep) {
new Expectations() {{
dep.put("key", "value"); // dep is null => NullPointerException !
}};
final ClassUnderTest c = new ClassUnderTest();
c.register("key", "value");
}
}
If I replace the HashMap with any POJO, JMockIt can mock it and the test will succeed. In fact, it appears that JMockit can't mock any concrete class (nor class that derive that any concrete class) from the Java Collection Framework.
The following test case show this problem:
public class MyTests {
public static class POJO {
}
public static class MyMapExtendingConcreteCollection extends HashMap<String, String> {
}
public static class MyMapExtendingAbstractCollection extends AbstractMap<String, String> {
@Override
public Set<java.util.Map.Entry<String, String>> entrySet() {
return null;
}
}
@Test
public void strangeBehaviors(@Mocked POJO mockedPOJO, @Mocked HashMap<String, String> mockedMap,
@Mocked ConcurrentHashMap<String, String> mockedConcurrentMap,
@Mocked MyMapExtendingConcreteCollection mockedMyMapFromConcrete,
@Mocked MyMapExtendingAbstractCollection mockedMyMapFromAbstract) {
assertNotNull(mockedPOJO); // OK : not null
assertNotNull(mockedMap); // FAIL: null !
assertNotNull(mockedConcurrentMap); // OK : not null
assertNotNull(mockedMyMapFromConcrete); // FAIL: null !
assertNotNull(mockedMyMapFromAbstract); // OK: not null
}
}
Will I misunderstand something in using JMockit ?
Thanks for your help.
Aucun commentaire:
Enregistrer un commentaire