我有一个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));
}
}
我相信测试已通过,但没有任何验证,对吗?这不应该-回来就足够了吗?
答案 0 :(得分:1)
我个人不会将存储库当作间谍,因此在设置中我将拥有:
@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方法,可订阅并创建一个测试观察器,该观察器可让您对不同的事件进行断言。
此外,我之所以不让存储库成为间谍,是因为您真的不需要验证与其进行任何交互,只需验证其依赖项即可。