问题1
编写测试函数运行时出现错误:No tests found for given includes:
@Test
void getPostsTest() throws IOException {
log.e("xxx", "hello world");
}
解决
方法没有声明为public
。本地测试中只能运行那些声明为public
的测试用例。
问题2
在单元测试中使用log
打印日志报错
解决
由于是本地测试,代码运行在本地的java
虚拟机上,所以不能直接使用安卓的api
,log
属于安卓的api
,改为System.out
问题3
使用retrofit
进行网络请求测试通过,但无法接收到结果
@Test
public void getPostsTest() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GetPost getPost = retrofit.create(GetPost.class);
Call<List<JsonObject>> call = getPost.getPostByNewest("post_date", 0);
call.enqueue(new Callback<List<JsonObject>>() {
@Override
public void onResponse(Call<List<JsonObject>> call, Response<List<JsonObject>> response) {
System.out.Println(response.body().toString());
}
@Override
public void onFailure(Call<List<JsonObject>> call, Throwable t) {
System.out.Println("request failed");
}
});
}
解决
由于采用的是call
的enqueue
方法,enqueue
是异步请求,对于异步请求,在测试中无法直接取得结果。
将call
改为同步方法即可,使用call.execute()
@Test
public void getPostsTest() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GetPost getPost = retrofit.create(GetPost.class);
Call<List<JsonObject>> call = getPost.getPostByNewest("post_date", 0);
Response<List<JsonObject>> res = call.execute();
System.out.println(res.body().toString());
}