gpt4 book ai didi

spring - MockMvc 返回 null 而不是对象

转载 作者:行者123 更新时间:2023-12-02 05:59:18 24 4
gpt4 key购买 nike

我正在开发一个微服务应用程序,我需要测试一个发布请求到 Controller 。手动测试可以工作,但测试用例总是返回 null。

我在 Stackoverflow 和文档中读到了很多类似的问题,但还没有弄清楚我错过了什么。

以下是我目前拥有的以及我为使其发挥作用而尝试的方法:

//Profile controller method need to be tested
@RequestMapping(path = "/", method = RequestMethod.POST)
public ResponseEntity<Profile> createProfile(@Valid @RequestBody User user, UriComponentsBuilder ucBuilder) {
Profile createdProfile = profileService.create(user); // line that returns null in the test
if (createdProfile == null) {
System.out.println("Profile already exist");
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/{name}").buildAndExpand(createdProfile.getName()).toUri());
return new ResponseEntity<>(createdProfile , headers, HttpStatus.CREATED);
}

//ProfileService create function that returns null in the test case
public Profile create(User user) {
Profile existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "profile already exists: " + user.getUsername());

authClient.createUser(user); //Feign client request

Profile profile = new Profile();
profile.setName(user.getUsername());
repository.save(profile);

return profile;
}

// The test case
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProfileApplication.class)
@WebAppConfiguration
public class ProfileControllerTest {

@InjectMocks
private ProfileController profileController;

@Mock
private ProfileService profileService;

private MockMvc mockMvc;

private static final ObjectMapper mapper = new ObjectMapper();

private MediaType contentType = MediaType.APPLICATION_JSON;

@Before
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(profileController).build();
}
@Test
public void shouldCreateNewProfile() throws Exception {

final User user = new User();
user.setUsername("testuser");
user.setPassword("password");

String userJson = mapper.writeValueAsString(user);

mockMvc.perform(post("/").contentType(contentType).content(userJson))
.andExpect(jsonPath("$.username").value(user.getUsername()))
.andExpect(status().isCreated());

}
}

尝试在发布之前添加 when/thenReturn 但仍然返回带有 null 对象的 409 响应。

when(profileService.create(user)).thenReturn(profile);

最佳答案

您在测试中使用了模拟 profileService,并且您从未告诉该模拟要返回什么。所以它返回 null。

你需要类似的东西

when(profileService.create(any(User.class)).thenReturn(new Profile(...));

请注意使用

when(profileService.create(user).thenReturn(new Profile(...));

仅当您在 User 类中正确重写 equals() (和 hashCode())时才有效,因为 Controller 接收到的实际 User 实例是您在测试中拥有的用户的序列化/反序列化副本,而不是同一个实例。

关于spring - MockMvc 返回 null 而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832097/

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