前言
在进行单元测试连接虚拟机中的 elasticsearch
,出现了一堆小问题,前前后后花了我一个多小时
原因各有千秋,这里只给出我遇到的情况
原因:springboot的版本和springcloud的版本不一致导致
需要添加这个注解:@RunWith(SpringRunner.class)
//注释掉import org.junit.jupiter.api.Test; 使用下面这句
import org.junit.Test;
要在类上和方法上添加public
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 {@Autowiredprivate RestHighLevelClient client;@Testpublic 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);}@Dataclass User{private String userName;private String gender;private Integer age;}@Testpublic void contextLoads() {System.out.println(client);}}