安卓本地代码测试踩坑20230323

问题1

编写测试函数运行时出现错误:No tests found for given includes:

@Test
void getPostsTest() throws IOException {
        log.e("xxx", "hello world");
    }

解决

方法没有声明为public。本地测试中只能运行那些声明为public的测试用例。


问题2

在单元测试中使用log打印日志报错

解决

由于是本地测试,代码运行在本地的java虚拟机上,所以不能直接使用安卓的apilog属于安卓的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");
            }
        });
    }

解决

由于采用的是callenqueue方法,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());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值