我有一个ApiRepository类,它将包含我所有的API调用,但目前只有一个:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient= restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
RestClient 界面看起来像这样:
public interface SrsRestClient {
@POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(@Header("Authorization") String authKey, @Body AuthRequestEntity requestEntity);
}
因此,我尝试运行通过的测试,但是当我生成代码覆盖率报告时,返回的代码行是红色的。
这是我的测试类:
public class RestApiRepositoryTest {
private RestApiRepository restApiRepository;
@Mock
private RestClient restClient;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
restApiRepository = Mockito.spy(new RestApiRepository(restClient));
}
@Test
public void test_success() {
String token = "token";
AuthRequestEntity requestEntity = new AuthRequestEntity();
AuthResponseEntity responseEntity = new AuthResponseEntity();
Mockito.when(restClient.postAuthObservable(token, requestEntity)).thenReturn(Observable.just(responseEntity));
}
}
我相信测试通过了,但没有任何验证,对吧?这不应该是什么时候 - 那么返回就足够了?
就个人而言,我不会使存储库成为间谍,因此在设置中我将拥有:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
restApiRepository = new RestApiRepository(restClient);
}
现在我会像这样编写测试:
@Test
public void test_success() {
String token = "token";
AuthRequestEntity requestEntity = new AuthRequestEntity();
AuthResponseEntity responseEntity = new AuthResponseEntity();
Mockito.when(restClient.postAuthObservable(token, requestEntity)).thenReturn(Observable.just(responseEntity));
restApiRepository.authenticate(token, responseEntity)
.test()
.assertValue(responseEntity)
}
通过这种方式,您断言可观察量发出所需的值。test
是一个方便的 Rx 方法,它订阅并创建一个测试观察器,允许您断言不同的事件。
此外,我不会使存储库成为间谍的原因仅仅是因为您实际上不需要验证与它的任何交互,只需验证其依赖项即可。