如何在其他方法调用中使用传递参数?

时间:2017-06-05 07:51:41

标签: java mockito

我已经读过我可以使用Answer对象,但在我的情况下存在问题。情况是这样的:

  

SecondObject secondObject = firstObject.getByType(String type);

然后

  

List list = secondObject.getSomeOtherValues();

实际上我想在模拟type的调用时使用参数secondObject。这可能吗?

1 个答案:

答案 0 :(得分:1)

做类似的事情:

when(firstObject.getByType(anyString())).thenAnswer(
     new Answer() {
         public Object answer(InvocationOnMock invocation) {
             String type= invocation.getArguments()[0];
             SecondObject  second = Mockito.mock(SecondObject  );

             //do something
            if(type== ....){
                when(second.getSomeOtherValues() ).thenReturn(....)
            } else{
                .....................................
            }


             return second ;
         }
 });

SecondObject secondObject = firstObject.getByType(String type);

我还没有测试过,但关键是

 if(type== ....){
        when(second.getSomeOtherValues() ).thenReturn(....)
    } else{
        .....................................
    }

mockito的主页回答http://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/stubbing/Answer.html

相关问题