java - 模拟返回错误的集合
问题描述
我想用我的模拟对象返回一个填充的地图,但地图的大小总是空的。模拟的对象“CommandLineValues options”不是 Null,而且我可以成功模拟的布尔变量“doCleanFirst”。
这是我的测试类:
@RunWith(MockitoJUnitRunner.class)
public class IndexBMECatTest {
@InjectMocks
private IndexBMECat classUnderTest;
@Mock
private CommandLineValues options;
@Test
public void testAccessoryItemHasNoDublicates() {
Map<String, String> testMap = new HashMap<>();
testMap.put("key", "value");
when(options.getCleanFirst()).thenReturn(false);
when(options.readWhitlist()).thenReturn(testMap);
classUnderTest.run();
}
}
这是我的代码开始的类的构造函数,测试的方法不相关:
private boolean doCleanFirst;
private Map<String, String> whiteList;
public IndexBMECat(TransportClient client, CommandLineValues options, BMECatReader reader) throws Exception {
this.doCleanFirst = options.getCleanFirst();
this.whiteList = options.readWhitlist();
if (whiteList.isEmpty()) {
throw new Exception("Missing whiteList");
}
}
我还尝试了其他变体:
- 模拟地图和方法“isEmpty”的返回值
- 初始化 Testclass 并将模拟的 Object 交给构造函数
但是白名单的大小总是= 0
解决方案
Thx,这现在有效:
private IndexBMECat classUnderTest;
@Mock
private CommandLineValues options;
@Mock
private BMECatReader reader;
@Mock
TransportClient client;
@Before
public void setUp() throws Exception {
Map<String, String> testMap = new HashMap<>();
testMap.put("key", "value");
when(options.getCleanFirst()).thenReturn(false);
when(options.readWhitlist()).thenReturn(testMap);
classUnderTest = new IndexBMECat(client, options, reader);
}
@Test
public void testAccessoryItemHasNoDublicates() {
classUnderTest.run();
}
首先,我模拟将在构造函数中执行的方法,然后创建我的测试类的实例。
推荐阅读
- azure - DotNetCoreCLI 可以构建解决方案吗?
- reactjs - 仅获取前 x 个元素 JavaScript / React
- c++ - 将模板类的实例添加到向量 (C++)
- java - 锁定文件系统上的并发访问
- html - 如何将 :hover 添加到导航栏上的图像?
- javascript - 带有 Javascript 和 MYSQL 的 Springboot
- angular - 如何在Angular 10中将字符串变量扩展为html内容?
- cocos2d-x - 带有 box2d 联系人监听器的 cocos2dx 不起作用
- android - 在特定片段中隐藏工具栏(在 appbar 布局内)
- c - 从 C 系统命令打开 vim