我开发一个微服务应用程序,我需要测试POST请求 到控制器。测试手动工作,但测试用例总是返回null。MockMvc返回null,而不是对象
我在#1和文档在这里读到很多类似的问题,但还没有想出我还缺少什么。
这是我现在有什么,我试图以使其工作:
//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);
由于错误说你已经在数据库中 – developer
测试用例内存数据库使用的,通常没有启动任何项目得到了用户的详细信息。 – user3127632