您的位置:首页 > 编程语言 > Java开发

springboot+Junit测试rest接口,报错显示url无法连接

2017-08-02 16:52 1036 查看
代码很简单,因为只是测试路径嘛!!!

看代码:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.client.RestTemplate;
import com.pcitc.domainname.servicename.Application;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class DemoApplicationTests{

private RestTemplate template = new TestRestTemplate();
/**
* @author PQF
*/
@Test
public void testMasterDataControllerQueryMasterDataByCode(){
try {
String url = "http://localhost:"+8081+"/v1/masterdata/0501080060000116";
String result = template.getForObject(url, String.class);
System.err.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}


运行DemoApplicationTests后,打断点,发现url报错,说是无法连接?????
于是各种上网找答案,没人告诉你是为什么。

今天我就写下这个答案。那是因为你没有启动主类,什么是主类???就是下面这个:

@RestController
@SpringBootApplication
@SpringBootConfiguration
@EnableCaching
public class Application{

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}


你要先启动主类,然后再启动Junit的测试类才可以。以上就是要注意的事项。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息