使用Mockito进行Mock Retrofit服务会导致ExceptionInInitializerError

时间:2015-07-02 15:49:25

标签: android unit-testing testing mockito retrofit

我尝试过:

androidTestCompile 'org.mockito:mockito-core:2.0.26-beta'

...

public interface CustomerService {
    @POST("url")
    Observable<Session> createSession(@Body Credential credential);
}

...

@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginActivityTests {

    @Before
    public void setUp() {
        customerService = Mockito.mock(CustomerService.class);
    }

    @Test
    public void testLoginGoToNextScreen() throws Exception {
       doReturn(new Session"token")).when(customerService).createSession(
           new Credential("aa", "123", new Device("asd", ":)")));
    }

但它总是崩溃。

java.lang.ExceptionInInitializerError
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.<init>(ConditionalStackTraceFilter.java:17)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:41)
at org.mockito.exceptions.base.MockitoException.<init>(MockitoException.java:30)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:35)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:12)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:11)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:23)
at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:44)
at org.mockito.Mockito.<clinit>(Mockito.java:1101)
at com.pickupnow.customer.LoginActivityTests.setUp(LoginActivityTests.java:48)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:257)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:54)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:228)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)
Caused by: java.lang.NullPointerException
at org.mockito.internal.configuration.plugins.Plugins.getStackTraceCleanerProvider(Plugins.java:17)
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.<clinit>(StackTraceFilter.java:21)
... 41 more

还有其他办法吗?

2 个答案:

答案 0 :(得分:2)

我总是测试:

when(customerService.createSession(any())).thenReturn(Observable.just(new Session("token")));

如果您需要指定必须使用的参数,而不是any(),则可以编写ArgumentMatcherhttp://mockito.googlecode.com/hg-history/1.6/javadoc/org/mockito/ArgumentMatcher.html)。我希望这会有所帮助。

答案 1 :(得分:0)

可以使用MockRestAdapter完成。

这很简单,只需创建一个MockedService来实现原始的Service声明,创建一个实例并将其设置为您的代码服务实例:

在每次测试之前......:

MockOrderService.mock(new Order("fake-data"))

模拟服务的示例:

public class MockOrderService implements OrderService {

    private Order mOrder;

    public static void mock(Order order){
        mOrder = order;

        // Setup MockRestAdapter without delays or posible errors
        MockRestAdapter mockRestAdapter = MockRestAdapter.from(ApiManager.REST_ADAPTER);
        mockRestAdapter.setDelay(0);
        mockRestAdapter.setErrorPercentage(0);
        mockRestAdapter.setVariancePercentage(0);

        // Create the mocked service and replace it in
        MockOrderService mockOrderService = new MockOrderService();
        mockOrderService.mOrder = order;

        // Replace the service instance with the mocked one
        // Then every time that the projec call Order.get will return what we 
        // had in our MockOrderService.get() code
        Order.SERVICE = mockRestAdapter.create(OrderService.class, mockOrderService);
    }

    // OrderService override
    @Override
    public Observable<Order> get(@Path("id") String id) {
        return Observable.just(mOrder);
    }

}

Order.SERVICE应该是项目用于请求的实例。

看一下这篇文章MakinGIANTS Post

<强> --- --- EDIT 如果您正在尝试进行单元测试,那么如果将改装服务包装在某种存储库中,则更容易进行模拟,那么您可以自行模拟存储库函数。