一、问题的现象
1、使用spring-boot-starter-test,执行测试时报错:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
二、解决方案
将测试类的包名修改与启动类的包名相同
例如:
测试类
package mediacomm;
import mediacomm.pojo.User;
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 org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringCloudTest {
@Autowired
private RestTemplate restTemplate;
@Test
public void httpGet(){
System.out.println("user = " + restTemplate.getForObject("http://localhost:8181/user/019419091b6440db8b4adb72d85548f2", User.class));
}
}
springboot启动类
package mediacomm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class mainApp {
public static void main(String[] args) {
SpringApplication.run(mainApp.class);
}
@Bean
public RestTemplate createTemplate() {
return new RestTemplate(); //URLConnetion
}
}