「真好用」SpringBootTest 和 junit.Test

以前 和 困扰

单元测试 得new对象去调用去测试 而且如果对象类 涉及@Autowire的bean注入 又得new

import org.junit.*;

public class EsClientTest {

    private static EsClient client;

    @Before
    public void setUp() throws Exception {
        client = new EsClient("");
    }
}


新使用

测试类上加上标签 即可直接@Autowire注入bean直接去测试 去调用了

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)


废话不多说直接上代码

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
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(classes = Application.class)
public class EsTest {

    @Autowired
    private RestHighLevelClient client;

    @Test
    public void getIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("users");//user_index
        GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse.getAliases());
        System.out.println(getIndexResponse.getMappings());
        System.out.println(getIndexResponse.getSettings());
        client.close();
    }
}



附上依赖

        
        
            org.springframework.boot
            spring-boot-test

        

        
        
            org.springframework
            spring-test

            test
        
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章