[英]Testing a map contained in a mocked class
我正在尝试测试ExampleController
类,该类的工作方式类似于POJO Example
类的外观。
我开始为ExampleController
编写InstrumentedTest
,因为它可以与Greenrobots EventBus一起使用,并且在尝试检索Example
类中存储在Map
中的值时遇到了NullPointerException
。
我使用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());
}
}
当我运行测试类时,得到以下输出:
java.lang.AssertionError:
Expected :1
Actual :0
由于我是测试的新手,所以我不知道哪里出错了。 当我搜索单元测试列表时,我只会找到对象中未包含的列表的测试。
您不能使用那样的“ getMap”方法,因为您在ExampleController中模拟了Example类。 您可以通过在方法前添加以下内容来解决此问题:
HashMap<Integer, String> mapInMock = new HashMap<>();
when(example.getMap()).thenReturn(mapInMock);
这样,您就告诉模拟的示例在调用getter时返回该hashMap。
我无法立即在javadoc中找到它,但是调试测试显示该地图在每次调用exampleController.getMap()之后都会返回一个新地图。 这就解释了为什么您无法在地图中获得任何内容并随后使用exampleController对其进行检索。
除了这是解决方案之外,您还可以怀疑是否确实需要模拟Example类。 您也可以只实例化它,除非您实际上想模拟它的某些部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.