마이크로 서비스 응용 프로그램을 개발 중이며 컨트롤러에 게시물 요청 을 테스트해야합니다. 수동 테스트는 작동하지만 테스트 케이스는 항상 null을 반환합니다.MockMvc가 객체 대신 null을 반환합니다.
여기 Stackoverflow 및 설명서에서 많은 유사한 질문을 읽었지만 아직 실종 된 것을 알아 냈습니다. 여기
내가 현재 가지고 내가 무엇을 위해 노력하는 것은 그것이 작동되도록하는 것입니다 : 게시하기 전에when
/
thenReturn
를 추가하지만 여전히 널 객체 (409) 응답을 반환하는 시도
//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(profileService.create(user)).thenReturn(profile);
데이터베이스에 사용자 세부 정보가 이미 있습니다. – developer
테스트 사례는 메모리 데이터베이스를 사용하며 일반적으로 시작시 엔트리가 없습니다. – user3127632