Mockito输出"想要但未被调用,实际上与这个模拟器没有任何交互"

时间:2018-03-27 17:18:48

标签: android mockito

我收到此错误:

Wanted but not invoked:
view.showPlayerActivity(null);
Actually, there were zero interactions with this mock.

我有这段代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Log.class)
public class MyDriverPresenterTest  {

    @Mock
    private MyDriveRepository mydriveRepository;

    private MyDrivePresenter drivePresenter;

    private Drive drive;

    private List<Drive> driveList;

    @Before
    public void setUpMyRecrdingsPresenter(){

        PowerMockito.mockStatic(Log.class);
        MockitoAnnotations.initMocks(this);

        drivePresenter = new MyDrivePresenter();

        drive = new Drive("Roar",false,1521708960,11);
        driveList.add(drive);

    }

    @Test
    public void testDriveClicked(){
        Uri uri=mydriveRepository.
        getMyDriveItemSelectedPathUri(drive.toFile().getName());
        verify(view).showPlayerActivity(uri);       
    }

}

类MyDrivePresenter有方法

@Override
    public void onDriveClicked(Drive drive) {
        Uri uri = mydriveRepository.getMyDriveItemSelectedPathUri(drive.toFile().getName());
        Log.i("TAG", "onRecordingClicked: "+uri);
        view.showPlayerActivity(uri);
    }

和MyDriveRepository有方法

public Uri getMyDriveItemSelectedPathUri(String name){
        Uri pathUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            pathUri = FileProvider.getUriForFile(context,"com.mypackagename",new File(getUserMixDir(),name));
        }else{
            pathUri = Uri.parse("file://"+new File(getUserMixDir(),name));
        }

        return pathUri;
    }

mydriveRepository.getMyDriveItemSelectedPathUri不断返回null。 我尝试查看以下链接https://stackoverflow.com/questions/20551926/exception-mockito-wanted-but-not-invoked-actually-there-were-zero-interaction?rq=1,但无法找到解决问题的方法。

1 个答案:

答案 0 :(得分:2)

看起来您正在嘲笑您的存储库,因此您需要提供演示者何时调用存储库方法的行为:

push_fill

所以你的测试看起来像这样:

when(mydriveRepository.getMyDriveItemSelectedPathUri(anyString())).thenReturn(mockedUri);

所以基本上你在这里测试演示者是否使用伪生成的URI调用该视图方法。当演示者调用存储库上的getMyDriveItemSelectedPathUri方法时,您告诉框架(mockito)返回模拟的URI。然后,当您测试视图中的方法是否由演示者调用时,将进行真正的测试。