我開發一個微服務應用程序,我需要測試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