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

来源:互联网 发布:excel同一列重复数据 编辑:程序博客网 时间:2024/06/08 16:05

代码很简单,因为只是测试路径嘛!!!

看代码:

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)@WebAppConfigurationpublic 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@EnableCachingpublic class Application{public static void main(String[] args) throws Exception {SpringApplication.run(Application.class);}}

你要先启动主类,然后再启动Junit的测试类才可以。以上就是要注意的事项。



原创粉丝点击