【问题标题】:How to create a unit test for a GET Rest service (Spring)如何为 GET Rest 服务创建单元测试(Spring)
【发布时间】:2020-07-20 12:11:11
【问题描述】:
我开发了一个应用程序,将书籍存储在 MongoDb 中,数据从用户的控制台获取,并直接保存到 MongoDb。 Book 对象的所有细节都传递给 Angular 前端,我使用 Spring 来制作 api。
@RestController
@RequestMapping("/api")
public class Controller {
@Autowired
BookRepository bookRepo;
@GetMapping("/books")
public List<Book> getBooks(){
return bookRepo.findAll();
}
}
API 工作正常,没有任何错误。(使用邮递员检查,可以从 Angular 站点查看数据)
现在我必须为这个 Controller 类编写一个单元测试。我对测试的了解非常低,请帮助我。提前致谢。
【问题讨论】:
标签:
java
spring
unit-testing
testing
junit
【解决方案1】:
您可以尝试以下代码进行单元测试。
@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@InjectMocks
private Controller controller;
@Mock
BookRepository bookRepo;
@Before
public void Setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void testGetBooks(){
Book book1 = new Book();
book1.setBookId(101L);
Book book2 = new Book();
book2.setBookId(102L);
List<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
Mockito.when(bookRepo.findAll()).thenReturn(books);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/books")
.accept(MediaType.APPLICATION_JSON);
mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk());
Mockito.verify(bookRepo, times(1)).findAll();
}
}