无法模拟方法

时间:2017-05-11 09:15:59

标签: java unit-testing mockito amazon-dynamodb

@Component
class ClassA{

    @Autowired
    ClassB classB;
     public void doSomething(){
         classD.createValues(a,b);
         //create values calls ClassB method
     }
}

@Component
class ClassB{

    @Autowired
    DynamoDBMapper mapper;

    public void doSomething(){
        mapper.scan(classC.class,new DynamoDBScanExpression()).stream();
    }

}  

测试类

 @RunWith(SpringJUnit4ClassRunner.class)
 class TestClass{

    @InjectMocks
    @Autowired
    ClassA classA;

    @Mock 
    ClassD classD;

    @Autowired
    @Qualifier("dynamodbMapper")
    private DynamoDBMapper mockedDynamoDBMapper;
    // globally mocked in config

        @Test
        public void testWithValidData() {
            A a = new A();
            B b = new B();
            setUp(classA);
            mockDynamoDBCall();
            classA.doSomthing();
        }

           private void setUp(ClassA classA){
               Mockito.when(classD.createValues(a,b)).thenReturn(Matchers.any(Reponse.class)); // problem after mockDynamoDBCall()
           }
           private void mockDynamoDBCall(){
               when(mapper.scan(Mockito.eq(Object.class), Mockito.any(DynamoDBScanExpression.class))).
               thenReturn(mockPaginatedScanList);
               when(mockPaginatedScanList.stream()).thenReturn(createDummyData().stream());
           }
 }

当我没有嘲笑DynamoDBMapper它的工作正常。

模拟DynamoDB映射器后,它在setUp方法

中抛出异常
[junit]     Caused an ERROR
[junit]
[junit] Invalid use of argument matchers!
[junit] 2 matchers expected, 1 recorded:
[junit] -> at  <class name>
[junit]
[junit] This exception may occur if matchers are combined with raw values:
[junit]     //incorrect:
[junit]     someMethod(anyObject(), "raw String");
[junit] When using matchers, all arguments have to be provided by matchers.
[junit] For example:
[junit]     //correct:
[junit]     someMethod(anyObject(), eq("String by matcher"));
[junit]
[junit] For more info see javadoc for Matchers class.
[junit]
[junit] org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
[junit] Invalid use of argument matchers!
[junit] 2 matchers expected, 1 recorded:
[junit] -> at <class name>
[junit]
[junit] This exception may occur if matchers are combined with raw values:
[junit]     //incorrect:
[junit]     someMethod(anyObject(), "raw String");
[junit] When using matchers, all arguments have to be provided by matchers.
[junit] For example:
[junit]     //correct:
[junit]     someMethod(anyObject(), eq("String by matcher"));

我尝试将Matchers.any(ClassName)和Matcher.any()作为参数传递但仍然得到相同的异常

1 个答案:

答案 0 :(得分:2)

这一行

 Mockito.when(classD.createValues(a,b)).thenReturn(Matchers.any(Reponse.class));

毫无意义。你必须告诉Mockito要返回什么。你不能告诉它返回任何Response.class。这不是匹配者所做的。

匹配器用于检查传递给方法的参数。它们无法在thenReturn之后使用。

如果你解决了这个问题,那么错误就会消失。