转载

使用Spring Boot REST API进行测试驱动开发

Maven插件rest-assured 是Java DSL测试REST服务,这个插件需要groovy-all来运行测试。

我们将添加maven-failsafe-plugin插件来执行集成测试:

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-failsafe-plugin</artifactId>
			<executions>
				<execution>
					<id>integration-test</id>
					<goals>
						<goal>integration-test</goal>
					</goals>
				</execution>
				<execution>
					<id>verify</id>
					<phase>verify</phase>
					<goals>
						<goal>verify</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<executions>
				<execution>
					<id>pre-integration-test</id>
					<goals>
						<goal>start</goal>
					</goals>
				</execution>
				<execution>
					<id>post-integration-test</id>
					<goals>
						<goal>stop</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

测试类代码如下:


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
@TestPropertySource(value={"classpath:application.properties"})
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class SpringRestControllerTest {
@Value(
"${server.port}")
int port;
@Test
public void getDataTest() {
get(
"/api/tdd/responseData").then().assertThat().body("data", equalTo("responseData"));
}
@Before
public void setBaseUri () {
RestAssured.port = port;
RestAssured.baseURI =
"http://localhost"; // replace as appropriate
}
}

@RunWith(SpringJUnit4ClassRunner.class)支持加载Spring应用程序上下文。

@ContextConfiguration 定义类级元数据,用于确定如何为集成测试加载和配置ApplicationContext。

@TestPropertySource 用于配置属性文件的位置。

@SpringBootTest 告诉Spring Boot去寻找一个主配置类(例如,一个带有@SpringBootApplication的类)并使用它来启动Spring应用程序上下文。

由于我们尚未定义REST端点,因此我们可以使用该mvn verify 命令运行上述测试 以查看测试失败。

让我们通过引入REST控制器来修复我们的测试:


@RestController
public class SpringRestController {
@RequestMapping(path = "/api/tdd/{data}", method= RequestMethod.GET)
public Response getData(@PathVariable(
"data") String data) {
return new Response(data);
}
//inner class
class Response {
private String data;
public Response(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
}

在上面的类中,我们有一个REST端点,它接受“data”作为输入,并在响应体中返回一个新的“Response”实例。

让我们mvn verify 再次运行命令。它现在应该成功运行测试。

原文  https://www.jdon.com/50043
正文到此结束
Loading...