我想编写控制器测试来测试我的注释。到目前为止,我所读到的是 RestAssured 是其中一种方法。
当我只有一个控制器测试时,它运行顺利。但是,当有 2 个或更多控制器测试类时,@MockBeans 似乎没有正确使用。根据测试执行顺序,第一个测试类中的所有测试都成功,而所有其他测试都失败。
在接下来的测试运行中,首先执行 PotatoControllerTest,然后是 FooControllerTest。
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles({"test", "httptest"})
class FooControllerTest {
@MockBean
protected FooService mockFooService;
@MockBean
protected BarService mockBarService;
@LocalServerPort
protected int port;
@BeforeEach
public void setup() {
RestAssured.port = port;
RestAssured.authentication = basic(TestSecurityConfiguration.ADMIN_USERNAME, TestSecurityConfiguration.ADMIN_PASSWORD);
RestAssured.requestSpecification = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.build();
}
@SneakyThrows
@Test
void deleteFooNotExists() {
final Foo foo = TestUtils.generateTestFoo();
Mockito.doThrow(new DoesNotExistException("missing")).when(mockFooService).delete(foo.getId(), foo.getVersion());
RestAssured.given()
.when().delete("/v1/foo/{id}/{version}", foo.getId(), foo.getVersion())
.then()
.statusCode(HttpStatus.NOT_FOUND.value());
Mockito.verify(mockFooService, times(1)).delete(foo.getId(), foo.getVersion());
}
...
}
Run Code Online (Sandbox Code Playgroud)
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) …Run Code Online (Sandbox Code Playgroud)