使用 SpringBootTest 注解
Using SpringBootTest annotation
我已经使用 Spring Boot 构建了一个 API 并且到目前为止有一些与之相关的单元测试。正如预期的那样,这些是 运行 在本地,当 Jenkins 在构建服务器上通过 gradle build
构建项目时。我希望现在使用 rest-assured 向项目添加一些集成测试,这样我就可以实际测试请求和响应,但我不太清楚如何将它们添加到项目中。
到目前为止,我已经向 src/test 添加了一个 integrationTests 文件夹,并告诉 gradle 在 gradle build
或通过 gradle test
时排除放心测试,所以我可以让他们保持独立。我已经设置了一个 gradle 任务 gradle integrationTest
来触发集成测试,只要 API 当前为 运行,它就可以正常运行。
显然我可以用 @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
注释测试 class 以指示 spring 启动嵌入式服务器进行自动测试,但它似乎没有做任何事情,测试只是失败并出现 java.net.ConnectException
错误,直到我在另一个 window 中启动 API。下面的示例代码有什么问题还是我遗漏了什么?
com.example.restassured;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import static io.restassured.RestAssured.*;
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class RunSomeTestsIT {
@Test public void url_should_return_200_response() {
get("/v1/test/123456").then().statusCode(200);
}
}
build.gradle
task integrationTest(type: Test) {
include 'com/example/restassured/**'
// Run all tests each time. Do not cache.
outputs.upToDateWhen { false }
}
co-incidence本人是working on something very similar today,希望能提供一些有用的指点。
当我与 this code 进行比较时,我认为您缺少 @RunWith(SpringRunner.class)
注释!
编辑:除了将测试移动到与 "Application" class 相同的包之外,您还可以尝试 Spring "first-principles" 方法 side-steps Spring 注释的所有 black-magic。至少你可以更好地解决问题并控制正在发生的事情:
我已经使用 Spring Boot 构建了一个 API 并且到目前为止有一些与之相关的单元测试。正如预期的那样,这些是 运行 在本地,当 Jenkins 在构建服务器上通过 gradle build
构建项目时。我希望现在使用 rest-assured 向项目添加一些集成测试,这样我就可以实际测试请求和响应,但我不太清楚如何将它们添加到项目中。
到目前为止,我已经向 src/test 添加了一个 integrationTests 文件夹,并告诉 gradle 在 gradle build
或通过 gradle test
时排除放心测试,所以我可以让他们保持独立。我已经设置了一个 gradle 任务 gradle integrationTest
来触发集成测试,只要 API 当前为 运行,它就可以正常运行。
显然我可以用 @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
注释测试 class 以指示 spring 启动嵌入式服务器进行自动测试,但它似乎没有做任何事情,测试只是失败并出现 java.net.ConnectException
错误,直到我在另一个 window 中启动 API。下面的示例代码有什么问题还是我遗漏了什么?
com.example.restassured;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import static io.restassured.RestAssured.*;
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class RunSomeTestsIT {
@Test public void url_should_return_200_response() {
get("/v1/test/123456").then().statusCode(200);
}
}
build.gradle
task integrationTest(type: Test) {
include 'com/example/restassured/**'
// Run all tests each time. Do not cache.
outputs.upToDateWhen { false }
}
co-incidence本人是working on something very similar today,希望能提供一些有用的指点。
当我与 this code 进行比较时,我认为您缺少 @RunWith(SpringRunner.class)
注释!
编辑:除了将测试移动到与 "Application" class 相同的包之外,您还可以尝试 Spring "first-principles" 方法 side-steps Spring 注释的所有 black-magic。至少你可以更好地解决问题并控制正在发生的事情: