2016-07-08 69 views
0

我正在爲我的春控制器寫JUnits。在其中一種情況下,我正在測試控制器內的版本。我嘲笑服務拋出一個RuntimeException。其他測試檢查成功輸出。方法嘲笑仍然爲其他測試

單獨的兩個測試都可以工作,但是當我一起執行時,如果第一個測試首先執行,那麼第二個測試也會拋出RuntimeException。我有什麼需要註銷嘲笑的方法嗎?

(請忽略語法)

class UserController { 
    @Autowired 
    UserService service; 

    @RequestMapping("...") 
    public ResponseEntity getUser(){ 
    try{ 
     User user = service.getUserAttributes(); 
     return new ResponseEntity(user, HttpStatus.OK); 
    } 
    catch(Exception e){ 
     return new ResponseEntity("Eror", HttpStatus.BAD_REQUEST); 
    } 
    } 
} 


@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes=TestConfig.class) 
public class UserControllerDocumentation { 
    @Autowired 
    private WebApplicationContext webApplicationContext; 
    private RestDocumentationResultHandler document; 
    private MockMvc mockMvc; 

    @Rule 
    public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets"); 

    @Autowired 
    UserService userService; 

    @Before 
    public void setUp(){ 
    this.document = document("{method-name}", preprocessRequest(prettyPrint()), 
       preprocessResponse(prettyPrint())); 
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext) 
     .apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document) 
     .build(); 
    } 


@Test 
    public void textError() throws Exception { 
    when(userService.getUserAttributes(anyInt())).thenThrow(new RuntimeException()); 
    this.mockMvc.perform(get("/user/xxx") 
      .accept("application/xml")) 
      .andExpect(status().isBadRequest()); 
    } 

    @Test 
    public void textUser() throws Exception { 
    when(userService.getUserAttributes(anyInt())).thenReturn(mockUserObj); 
    this.mockMvc.perform(get("/user/10") 
      .accept("application/xml")) 
      .andExpect(status().isOk()); 
    } 

回答

0

原來,即使在拋出異常之後,我仍需要爲模擬方法返回一些東西。添加thenReturn(null)thenThrow

@Test 
    public void textError() throws Exception { 
    when(userService.getUserAttributes(anyInt())).thenThrow(new RuntimeException()).thenReturn(null); 
    this.mockMvc.perform(get("/user/xxx") 
      .accept("application/xml")) 
      .andExpect(status().isBadRequest()); 
    } 
0

我不知道該怎麼@Autowired的作品,但很明顯:你的類有userService一個實例;並且你的textError()測試用例將它配置爲引發異常。而當你的第二次測試運行時,這個「行爲規範」仍然存在並且會引發你。

因此,我看到兩個選項:

一)您使用或「前」方法重置userService

B)每個測試方法都有自己的userService「後」