一些解决方法如下:
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) public class MyActivityTest {
private MyActivity activity;
@Mock
private MyService myService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
activity = new MyActivity();
activity.setMyService(myService);
}
@Test
public void testMyService() {
Mockito.when(myService.doSomething()).thenReturn("Result");
activity.doSomething();
Mockito.verify(myService).doSomething();
}
}
在此示例中,我们使用Mockito库来模拟MyService类,并确保它已正确设置并注入到MyActivity中。然后,我们设置预期结果,并使用verify方法检查MyService是否已调用正确。