我正在开发一个微服务应用程序,我需要测试邮政请求到控制器。测试手动起作用,但测试案例总是返回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);
您在测试中使用模拟概要服务,而您永远不会告诉模拟要返回的内容。因此它返回null。
您需要
之类的东西when(profileService.create(any(User.class)).thenReturn(new Profile(...));
请注意,使用
when(profileService.create(user).thenReturn(new Profile(...));
仅在用户类中正确覆盖equals()()()()(hashcode())时,才能工作,因为控制器收到的实际用户实例是您在测试中所拥有的序列化/次要化副本同一实例。