提问者:小点点

rx java和Mockito不工作


当我执行以下操作时,我收到以下错误:

org.mockito.exceptions.missing.MissingMethodInvocationException:when()需要一个参数,该参数必须是“模拟上的方法调用”。例如:when(mock.getArticles()).thenReturn(articles);

如何模拟rx java对象?

     <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.11.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.reactivex.rxjava2</groupId>
        <artifactId>rxjava</artifactId>
        <version>2.1.7</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>


@RunWith(MockitoJUnitRunner.class)
public class UnitTestJunit4 {


@Mock
Session session;

@BeforeClass
public static void runOnceBeforeClass() {
    System.out.println("@BeforeClass - runOnceBeforeClass");
}

// Run once, e.g close connection, cleanup
@AfterClass
public static void runOnceAfterClass() {
    System.out.println("@AfterClass - runOnceAfterClass");
}

// Should rename to @BeforeTestMethod
// e.g. Creating an similar object and share for all @Test
@Before
public void runBeforeTestMethod() {

    System.out.println("@Before - runBeforeTestMethod");

    MockitoAnnotations.initMocks(this);
    when( session.getSession("a","b","c","d") )
      .thenReturn( Single.error( new Exception() ) );
}

// Should rename to @AfterTestMethod
@After
public void runAfterTestMethod() {
    System.out.println("@After - runAfterTestMethod");
}

@Test
public void test_method_1() {
    System.out.println("@Test - test_method_1");
}

@Test
public void test_method_2() {
    System.out.println("@Test - test_method_2");
}
}


public class Session {

public static Single<Session> getSession(String a, String b, 
  String c, String d) {
  return Single.<SessionObject>create(emitter -> { 
   emitter.onSuccess(new SessionObject());
  }
}

我试图模仿的会话类。


共1个答案

匿名用户

您需要使用PowerMockito,因为Session类中的getSession()方法是一个静态方法。不能使用Mockito模拟静态方法。

你可以这样使用PowerMockito,

>

  • 在Gradle中添加PowerMockito

    dependencies {
        testImplementation "org.powermock:powermock-module-junit4:1.6.6"
        testImplementation "org.powermock:powermock-module-junit4-rule:1.6.6"
        testImplementation "org.powermock:powermock-api-mockito2:1.7.0"
        testImplementation "org.powermock:powermock-classloading-xstream:1.6.6"
    }
    

    将此行添加到类的上方

    @PrepareForTest({Session.class})
    

    然后写一个像下面这样的测试方法,

    @Test
    public void testMethod() {
        PowerMockito.mockStatic(Session.class);
        PowerMockito.when(Session.getSession("a","b","c","d"))
           .thenReturn(Single.error(new Exception()));
    }
    

    希望这个答案有帮助。