【发布时间】:2018-06-21 23:57:25
【问题描述】:
执行以下操作时出现以下错误:
org.mockito.exceptions.misusing.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());
}
}
我试图模拟的会话类。
【问题讨论】:
-
我经常模拟返回 RxJava 对象的对象。你是说 Mockito 在抱怨
sessions?您确定它是您的测试上下文中的模拟对象吗?在您的调试会话中,检查sessions对象应该会显示其中某处包含Mock的类。 -
更新了上面的 Session 对象。你的测试上下文是什么意思?
-
Session::getSessionContext()和Session::getSession()是什么关系? -
抱歉两者都是一样的,贴这里之前简化了我的代码,所以方法名忘记改了
-
您是否阅读过 Mockito 的文档,上面说他们不模拟静态方法?我认为前进的方向是在 Mockito 之上使用 PowerMockito。