MockMvc返回null而不是object

时间:2016-11-27 18:00:32

标签: spring spring-mvc junit mockito microservices

我正在开发一个微服务应用程序,我需要测试一个post请求 到控制器。手动测试有效,但测试用例总是返回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);

1 个答案:

答案 0 :(得分:4)

您在测试中使用了模拟profileService,而且您永远不会告诉模拟返回什么。所以它返回null。

你需要像

这样的东西
when(profileService.create(any(User.class)).thenReturn(new Profile(...));

请注意使用

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

只有在User类中正确覆盖equals()(和hashCode())才有效,因为控制器接收的实际用户实例是测试中用户的序列化/反序列化副本,而不是相同的实例。