当前位置: 首页 > 知识库问答 >
问题:

Mockito输出“需要但没有调用,实际上与这个模拟没有任何交互”

耿炎彬
2023-03-14
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);       
    }

}
@Override
    public void onDriveClicked(Drive drive) {
        Uri uri = mydriveRepository.getMyDriveItemSelectedPathUri(drive.toFile().getName());
        Log.i("TAG", "onRecordingClicked: "+uri);
        view.showPlayerActivity(uri);
    }
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-actural-there-there-zero-interaction?rq=1,但没有找到解决问题的方法。

共有1个答案

陶修洁
2023-03-14

它看起来像是在嘲笑存储库,所以您需要在演示者调用存储库方法时提供一个行为:

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

因此,您的测试将如下所示:

@Mock
MyDriveRepository mydriveRepository;

@Mock
Uri mockedUri;


@Test
public void testDriveClicked() {
    String filePath = "aPAth";

    presenter.onDriveClicked(drive);
    Uri uri = mydriveRepository.getMyDriveItemSelectedPathUri(filePath);
    verify(view).showPlayerActivity(uri);
}

因此,基本上在这里,您将测试演示者是否使用伪生成的URI调用视图方法。当演示者调用存储库上的getMyDriveItemSelectedPathUri方法时,您将告诉框架(mockito)返回一个模拟URI。然后,当您测试视图中的方法是否被演示者调用时,才是真正的测试。

 类似资料: