gpt4 book ai didi

Spring Mockito: Null return on method call with specific arguments for repository mock(Spring Mockito:带有存储库模拟的特定参数的方法调用返回为空)

转载 作者:bug小助手 更新时间:2023-10-28 21:42:24 28 4
gpt4 key购买 nike



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.

我还想具体说明这个测试用例。


更多回答
优秀答案推荐

When you mock your repository, you pass the PageRequest object with only the page and size parameters, but in your controller you use PageRequest with the sort parameter. Therefore, your mocked repository will return null because it wasn't mocked for that type of PageRequest.
Change the PageRequest object in your test or leave the ArgumentMatcher as is for PageRequest and it should work.

当你模拟你的仓库时,你只传递了页面和大小参数的PageRequest对象,但是在你的控制器中,你使用了带有sort参数的PageRequest。因此,您的模拟存储库将返回null,因为它没有针对该类型的PageRequest进行模拟。在测试中更改PageRequest对象或保留PageRequest的ArgumentMatcher,它应该可以工作。


更多回答

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com