MockMvc返回null而不是对象

use*_*632 1 junit spring spring-mvc mockito microservices

我正在开发微服务应用程序,我需要测试对控制器的发布请求。手动测试有效,但是测试用例始终返回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());

    }
}
Run Code Online (Sandbox Code Playgroud)

尝试在发布前添加when/ thenReturn,但仍返回409响应(带有空对象)。

when(profileService.create(user)).thenReturn(profile);
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

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

你需要类似的东西

when(profileService.create(any(User.class)).thenReturn(new Profile(...));
Run Code Online (Sandbox Code Playgroud)

注意使用

when(profileService.create(user).thenReturn(new Profile(...));
Run Code Online (Sandbox Code Playgroud)

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