I try to mock the following repository and return a page of ToDo entries based on the name of the owner. I'm using 'org.springframework.boot' version '3.1.3'.
我尝试模拟以下存储库,并根据所有者的姓名返回一页TODO条目。我使用的是‘org.springFrawork.boot’版本‘3.1.3’。
@Repository
public interface NotioRepository extends CrudRepository<ToDo, Long>, PagingAndSortingRepository<ToDo, Long> {
Page<ToDo> findByOwner(String owner, Pageable pageable);
...
}
My controller looks like this:
我的控制器如下所示:
@RestController
@RequestMapping("/api/todos")
public class NotioController {
private final NotioRepository notioRepository;
public NotioController(NotioRepository notioRepository) {
this.notioRepository = notioRepository;
}
@GetMapping
public ResponseEntity<List<ToDo>> getToDos(Pageable pageable, Principal principal) {
Page<ToDo> page = notioRepository.findByOwner(
principal.getName(),
PageRequest.of(
pageable.getPageNumber(),
pageable.getPageSize(),
pageable.getSortOr(Sort.by(Sort.Direction.ASC, "done"))
)
);
return ResponseEntity.ok(page.getContent());
}
...
}
To reduce the time during tests I wanted to add some unit tests and only test the controller using the following test class:
为了减少测试期间的时间,我想添加一些单元测试,并且只使用以下测试类测试控制器:
@WebMvcTest(NotioController.class)
@ComponentScan(basePackages = {"com.example.controller"})
public class NotioControllerTests {
@Autowired
private MockMvc mvc;
@MockBean
private NotioRepository notioRepository;
@Test
@WithMockUser(roles="USER", username="tom")
public void shouldReturnAPageWithUserSpecificToDos() throws Exception {
ToDo[] toDos = {
new ToDo(0L, "Get milk.", false, "tom"),
new ToDo(1L, "Get bread.", true, "tom")
};
Page<ToDo> responsePage = new PageImpl<>(List.of(toDos));
when(notioRepository.findByOwner("tom", PageRequest.of(0,2)))
.thenReturn(responsePage);
mvc.perform(
get("/api/todos")
.param("page", "0")
.param("size", "2")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray());
}
The test method "shouldReturnAPageWithUserSpecificToDos" throws the following exception:
测试方法“shouldReturnAPageWithUserSpecificToDos”引发以下异常:
java.lang.NullPointerException: Cannot invoke "org.springframework.data.domain.Page.getContent()" because "page" is null
which occurs when return ResponseEntity.ok(page.getContent());
is called in the controller method.
在控制器方法中调用Return ResponseEntity.ok(page.getContent());时会发生这种情况。
However, when I change
然而,当我改变时
when(notioRepository.findByOwner("tom", PageRequest.of(0,2)))
.thenReturn(responsePage);
to
至
when(notioRepository.findByOwner(any(String.class), any(Pageable.class)))
.thenReturn(responsePage);
the exception is resolved.
则解决该异常。
I have not yet figured out what the problem is and could not find any help in the other posts about repositories returning null as they were slightly different problems.
我还没有弄清楚问题是什么,在其他关于存储库返回空的帖子中也找不到任何帮助,因为它们的问题略有不同。
I also like to be specific with this test case.
我还想具体说明这个测试用例。
更多回答
我是一名优秀的程序员,十分优秀!