我正在开发单元测试。 如果我在“运行”模式下开始测试,则运行失败,并显示以下消息:
This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(anyObject(), eq("String by matcher")); For more info see javadoc for Matchers class.
如果我在调试模式下使用String tableName = table.getTableName()上的断点运行测试,则测试通过得很好。停止发生在断点上。
@Test
void myTest() {
Table table = mock(Table.class);
when(table.getTableName()).thenReturn("mytableName")
SQLService service = new SQLService(table);
service.select();
}
class SQLService {
private final Table table;
SQLService(Table table) {
this.table = table;
}
void select() {
String tableName = table.getTableName(); // <---- issue here, breakpoint is set on this line
........
}
}
答案 0 :(得分:1)
此问题是由将匹配器与原始值混合引起的。如果使用匹配器,则需要对所有参数使用匹配器。
尝试使用.eq()匹配器,在您的代码中是这样的:
when(Mockito.eq(table.getTableName())).thenReturn("mytableName");