rx java 和 Mockito 不工作

rx java and Mockito not working

当我执行以下操作时出现以下错误:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个必须为 'a method call on a mock' 的参数。 例如: 当(mock.getArticles()).thenReturn(文章);

如何模拟 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());
  }
}

会话class,我试图在上面进行模拟。

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

你可以像这样使用 PowerMockito,

  1. 在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"
    }
    
  2. 在 class

    上方添加此行
    @PrepareForTest({Session.class})
    
  3. 然后写一个如下的测试方法,

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

希望这个回答对您有所帮助。