文章目录
前言
在进行单元测试连接虚拟机中的 elasticsearch
,出现了一堆小问题,前前后后花了我一个多小时
1、Docker中运行的服务
2、遇到问题
原因各有千秋,这里只给出我遇到的情况
第一个问题是项目直接启动失败?
原因:springboot的版本和springcloud的版本不一致导致
第二个问题是项目启动后获取不到注入的bean?
需要添加这个注解:@RunWith(SpringRunner.class)
第三个问题就是测试单元的引入问题?
//注释掉import org.junit.jupiter.api.Test; 使用下面这句
import org.junit.Test;
第四个问题就是公共类和方法?
要在类上和方法上添加public
3、这里是完整的代码部分(正确)
package com.atguigu.gulimall.search;
import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {
@Autowired
private RestHighLevelClient client;
@Test
public void indexData() throws IOException {
IndexRequest indexRequest = new IndexRequest("users");
indexRequest.id("id");
User user = new User();
user.setUserName("lisi");
user.setAge(18);
user.setGender("男");
String jsonString = JSON.toJSONString(user);
indexRequest.source(jsonString, XContentType.JSON);
//执行
IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//提取
System.out.println(index);
}
@Data
class User{
private String userName;
private String gender;
private Integer age;
}
@Test
public void contextLoads() {
System.out.println(client);
}
}
4、成功测试通过
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/131472.html