2016-11-27 315 views
1

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

由於錯誤說你已經在數據庫中 – developer

+0

測試用例內存數據庫使用的,通常沒有啓動任何項目得到了用戶的詳細信息。 – user3127632

回答

2

你在測試中使用了一個模擬profileService,並且你永遠不會告訴模擬返回什麼。所以它返回null。

你需要像

when(profileService.create(any(User.class)).thenReturn(new Profile(...)); 

注意,使用

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

將只有當你正確重寫equals()(和hashCode())在User類的工作,因爲實際的用戶例如,該控制器接收到的是你在你的測試讓用戶的序列化/反序列化複製,而不是同一個實例。

+0

無論任何(User.class)和重寫equals()/ hashCode()方法解決我的問題。非常感謝你。你認爲哪一個更適合用於這種情況? – user3127632

+0

我一般避免在實體定義的equals()和hashCode()。這會導致比解決問題更多的問題,並且很難爲他們找到一個好的實施方案。所以我會使用這裏或其他匹配器。 –