Spring Boot-单元测试未检测到控制器测试



我已经为控制器类编写了单元测试,但当我使用";mvn测试";或直接从";SpringBootDemo1ApplicationTests";仅在";SpringBootDemo1ApplicationTests";类运行,并且它不会从";BookControllerTest";班

SpringBootDemo1ApplicationTests.java:

package com.sprboot.SpringBootDemo1;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringBootDemo1ApplicationTests {
@Test
void contextLoads() {
}
}

BookControllerTest.java

package com.sprboot.SpringBootDemo1;
import com.sprboot.SpringBootDemo1.controllers.BookController;
import com.sprboot.SpringBootDemo1.models.Book;
import com.sprboot.SpringBootDemo1.services.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@AutoConfigureJsonTesters
@WebMvcTest(BookController.class)
@SpringBootTest
public class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BookService bookService;
@Autowired
private JacksonTester<Book> jsonBook;
@Test
private void canRetriveBookById() throws Exception {
given(bookService.getBookByID(123)).willReturn(Optional.of(new Book(123, "test book")));
MockHttpServletResponse response = mockMvc.perform(
get("/getBookById/123")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonBook.write(new Book(1, "test book")).getJson()
);
}
private void canRetriveBookByIdV2() throws Exception {
given(bookService.getBookByID(123)).willReturn(Optional.of(new Book(123, "test book")));
MockHttpServletResponse response = mockMvc.perform(
get("/getBookById/123")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonBook.write(new Book(1, "test book")).getJson()
);
}
}

我期待着测试";canRetriveBookById";也运行,但只测试";contextLoads";跑步,不确定这里出了什么问题。

这是因为您的@Test方法是私有的。

来自@Test注释文档:

@Test methods must not be private or static and must not return a value.

最新更新