Powermockito NotAMockException 即使对象是模拟



我试图模拟 Uri.parse(( 以始终返回一个模拟的 Uri 对象。不幸的是,我被告知,我试图返回的对象不是一个被嘲笑的对象,但我无法理解为什么。

我的代码:

package com.example.recyclerview;
import android.net.Uri;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Uri.class})
public class SimpleExampleTest {
@Test
public void setup(){
PowerMockito.mockStatic(Uri.class);
Uri uri = mock(Uri.class);
try {
// this line causes the error
PowerMockito.when(Uri.class, "parse", anyString()).thenReturn(uri);
// also tried line below, but still got the same error:
// PowerMockito.doReturn(uri).when(Uri.class, "parse", anyString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

My build.gradle:

// Unit Tests
//jUnit
testImplementation 'junit:junit:4.12'
//Mockito
testImplementation 'org.mockito:mockito-core:2.8.9'
// Mockito mock okHttp Response (and probably other final classes)
testImplementation 'org.mockito:mockito-inline:2.13.0'
// Json for mockito
testImplementation 'org.json:json:20140107'
// Instant executor rule
testImplementation "androidx.arch.core:core-testing:2.1.0"
// PowerMockito to extend Mockito for static methods
testImplementation "org.powermock:powermock-api-mockito2:2.0.5"
testImplementation "org.powermock:powermock-module-junit4:2.0.5"

这是我得到的错误:

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class

该错误似乎与Mockito/Powermockito问题有关。 为了解决这个问题,我不得不使用这些Mockito版本:

testImplementation 'org.mockito:mockito-core:2.23.4'
testImplementation "org.powermock:powermock-api-mockito2:2.0.0"
testImplementation "org.powermock:powermock-module-junit4:2.0.0"

另请参阅此处的讨论: https://github.com/powermock/powermock/issues/992#issuecomment-537439824

最新更新