MockMvc 返回 null 而不是对象

2024-02-09

我正在开发一个微服务应用程序,我需要测试一个发布请求 到控制器。手动测试可以工作,但测试用例始终返回 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在 post 之前但仍然返回 409 响应和 null 对象。

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())时才有效,因为控制器接收的实际 User 实例是您在测试中拥有的用户的序列化/反序列化副本,而不是同一个实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MockMvc 返回 null 而不是对象 的相关文章

随机推荐