我正在尝试测试ExampleController
类,它类似于我的POJO Example
类的外观。
我开始为InstrumentedTest
编写ExampleController
,因为它适用于Greenrobots EventBus,当我尝试检索存储在{{1}中的值时获得了NullPointerException
在我的Map
课程中
我使用Example
,Mockito v2.7.19
和Espresso 2.2.2
。
我使用以下示例设置在单元测试中重新创建了我的问题:
JUnit 4.12
测试类:
class Example {
private HashMap<Integer, String> map;
Example(){ map = new HashMap<>(); }
//getter and setter for map
}
class ExampleController {
private Example example;
ExampleController(Example example){ this.example = example; }
public HashMap<Integer, String> getMap(){ return example.getMap(); }
}
当我运行测试类时,我得到以下输出:
class ExampleControllerTest {
ExampleController exampleController;
@Before
public void setUp() throws Exception {
Example example = mock(Example.class);
exampleController = new ExampleController(example);
}
@Test
public void testPutThingsInMap() throws Exception {
HashMap<Integer, String> map = exampleController.getMap();
map.put(1, "Test");
exampleController.getMap().putAll(map);
assertEquals(1, exampleController.getMap().size());
}
}
由于我对测试比较陌生,我不知道哪里出错了。当我搜索单元测试列表时,我只找到对象中未包含的列表的测试。
答案 0 :(得分:2)
你不能像这样使用“getMap”方法,因为你在ExampleController中模拟了Example类。 您可以通过在before-method中添加以下内容来解决此问题:
HashMap<Integer, String> mapInMock = new HashMap<>();
when(example.getMap()).thenReturn(mapInMock);
这样你就可以告诉模拟的示例在调用getter时返回hashMap。
我无法在javadoc中立即找到它,但调试测试显示每次调用exampleController.getMap()后都会返回一个新映射。这就解释了为什么你不能在地图中获得任何东西,然后用你的exampleController检索它。
除了这个解决方案之外你还可以想知道你是否真的需要模拟Example类。您也可以实例化它,除非您真的想要模拟它的某些部分。