最近做测试代码,编译总是不通过报出下面的错误
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:70)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)
查了一下百度后来发现是测试代码与源代码 的package 不一样导致。
后来将他们的包名改为一样的就可以了
例如:
test
--package com.xxx.yyy.controller;
src
--package com.xxx.yyy.controller;
测试代码如下
package com.xxx.yyy.controller;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import com.alibaba.fastjson.JSON;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TestXXXController {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
private MockHttpSession session;
@LocalServerPort
private int port;
private String host = "http://localhost:";
private String path = "xxx";
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testList() throws UnsupportedEncodingException{
Map<String, Object> param =new HashMap<String, Object>();
param.put("id", 19);
param.put("menuId", "1");
StringBuffer sb = getParameterString(param);
String json = this.restTemplate.getForObject("http://localhost:" + port + "/xxx/ccc/list.json?"+sb.toString(),
String.class);
System.out.println(json);
}
}