注意:测试类中使用@Autowired注解注入Bean,不要使用@RequiredArgsConstructor注解注入Bean
正确示范:
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;@SpringBootTest
class ElasticSearchApplicationTests {@Autowired //注意点private ItemService itemService;}
错误示范:
import lombok.RequiredArgsConstructor;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
@RequiredArgsConstructor //注意点
class ElasticSearchApplicationTests {private final ItemService itemService;}
注意:如果启动多种环境配置的服务,在测试类中测试接口要指明其请求的服务配置文件的后半段名称,如application-dev.yml只需写dev。
正确示范:
import org.springframework.beans.factory.annotation.Autowired;
import com.example.elasticsearch.domain.po.Item;@SpringBootTest(properties = "spring.profiles.active=dev") //注意点
class ElasticSearchApplicationTests {@Autowiredprivate ItemService itemService;@Testvoid testAddDocument() throws IOException {// 根据id查询商品数据Item item = itemService.getById(317578L);System.out.println(item);}
}