简体   繁体   English

单元测试、调试和运行模式下的模拟对象

[英]Unit tests, Mock objects in Debug and in Run modes

I'm developing unit test.我正在开发单元测试。 If I start test in Run mode, the run is failed with message:如果我在运行模式下开始测试,运行失败并显示以下消息:

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.

If I run the test in Debug mode with the breakpoint on String tableName = table.getTableName() the test is passing well.如果我在调试模式下使用 String tableName = table.getTableName() 上的断点运行测试,则测试通过得很好。 The stop occurs on the breakpoint.停止发生在断点上。

@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
        ........    
    }
}

This issue is caused by mixing matchers with raw values.此问题是由将匹配器与原始值混合引起的。 If you use matchers then you need to use matchers for all arguments.如果您使用匹配器,那么您需要为所有参数使用匹配器。

Try and use the .eq() matcher, with your code it is something like this:尝试使用 .eq() 匹配器,你的代码是这样的:

when(Mockito.eq(table.getTableName())).thenReturn("mytableName");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM