spring-boot有关spring-boot测试的一些问题,
这测试的时候主程序没有启动报错。错误如下
==org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:39900/migrate/test": Connect to localhost:39900 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:39900 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)==
这是因为测试的类写了url 的问题
具体的测试方法如下
package api;
import com.hera.WebApplication;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class Test {
@Autowired
public TestRestTemplate restTemplate;
@org.junit.Test
public void home(){
String url="http://localhost:39900/migrate/test";
Map map=restTemplate.getForObject(url,Map.class);
System.out.println(map.get("red"));
}
}
主函数如下
@ComponentScan(basePackages={"com.hera"})
@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = ExtJpaRepositoryFactoryBean.class)
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
这样可以认为是服务没有启动的原因,确实,当服务启动的时候,这个错误就会没有,这时候可以得出一个结论,就是Test的时候主函数是没有启动。需要启动主函数参能测试,
但是有个问题就是
当测试时url不要http://localhost:39900没有起动主函数一样能成功
[INFO][2018-04-29T22:40:02.455+0800][BusinessHandlerInterceptor.java:28] 【LOG HANDLER】 url=http://localhost:63857/migrate/test, traceId=null
..............................
[INFO][2018-04-29T22:40:02.976+0800][BusinessHandlerInterceptor.java:48] 请求参数==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green
但是端口号不是配置中的那个,还有就是每次端口号都会不一样,真的很奇怪;根本不按照配置来的,我觉得就是它没有都配置,但是默认端口不是8080吗,现在是每次都变,只是随机的一个端口号,从这一面又能看出,其实测试不用单独启动主函数的,测试类会启动,访问不了是因为,端口号不对,但是至于怎么解决目前没有想到. 但是也不影响开发,因为我认为服务端都没启动,客户端怎么能访问呢。至于测试会加载springbootApplication但是端口不一样,没有执行加载端口类的结果。
………………………………………
………………………….