我用rest方法开发了一个Spring MVC webapp。我很乐意使用RestAssured来创建JUnit测试类。从文档中看起来很简单,但我遇到了一些问题。基本上我想用它来避免运行时Tomcat实例,但问题是当我执行JUnit测试类时,我得到以下异常:
org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8082 refused
...
Caused by: java.net.ConnectException: Connection refused
这是我的JUnit类:
import static com.jayway.restassured.RestAssured.given;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/test/resources/spring/application-test-config.xml"})
@WebAppConfiguration
public class ExternalControllerTest {
private static final Logger logger = LoggerFactory.getLogger(ExternalControllerTest.class);
@Autowired
WebApplicationContext webApplicationContext;
@Before
public void setUp() throws Exception {
RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
}
@Test
public void addClientDeviceId_Success() {
given().get("/api/test").then().statusCode(200);
}
}
我还尝试直接使用控制器类配置RestAssuredMockMvc但结果是一样的:
RestAssuredMockMvc.standaloneSetup(new ExternalController());
控制器看起来像这样:
@Controller
@RequestMapping("/api")
public class ExternalController {
public ExternalController() {
logger.info("ExternalController initialised!");
}
@RequestMapping(value="/test", method = RequestMethod.GET, produces={"application/json", "application/xml"})
public @ResponseBody DmsResponse test(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
return null;
}
}
在本指南中http://www.jayway.com/2014/01/14/unit-testing-spring-mvc-controllers-with-rest-assured/被指定为“最重要的方面是启动环境更简单。您不需要引导容器(例如Jetty或Tomcat),只需初始化RestAssuredMockMvc有一个上下文(例如一个控制器),你准备好了。“所以我不明白问题出在哪里。有什么建议吗?
使用Tomcat部署的war文件工作正常。 感谢
答案 0 :(得分:6)
您正在静态导入错误的方法。您正在从given
com.jayway.restassured.RestAssured
导入io.restassured.RestAssured
(如果使用的是版本3.x),但您应该从com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
(io.restassured.module.mockmvc.RestAssuredMockMvc
中静态导入方法版本3.x)。有关详细信息,请参阅documentation。