使用集成測試(谷歌Spring MVC的集成測試)
有點兒這個
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = YourApplication.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class SampleControllerTest {
@Value("${local.server.port}")
protected int port;
@Autowired
protected WebApplicationContext context;
private RestTemplate restTemplate = new RestTemplate();
@Test
public void returnsValueFromDb() {
// you should run mock db before
String id = "a0972ca1-0870-42c0-a590-be441dca696f";
String url = "http://localhost:" + port + "/call.action?id=" + id;
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
String body = response.getBody();
// your assertions here
}
}
在這篇文章請看:http://stackoverflow.com/questions/861089/testing-spring-mvc-annotation-mapppings – McStretch 2010-11-05 18:52:28