2017-08-05 82 views
0

我是使用Mockito進行單元測試的Spring Rest控制器的新手。這是我的控制器和我的測試代碼。無法模擬一個服務,讓它拋出一個異常

@RestController 
@RequestMapping("/api/food/customer") 
public class CustomerController { 
    @Autowired 
    private CustomerService service; 

    @RequestMapping(method=RequestMethod.POST, produces= MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<Customer> addCustomer(@RequestBody Customer c){ 
     Logger log = LoggerFactory.getLogger(CustomerController.class.getName()); 
     try { 
      service.addCustomer(c); 
     } catch (UserNameException e){ 
      log.error("UserNameException", e); 
      return new ResponseEntity(HttpStatus.BAD_REQUEST); 
     } catch (Exception e){ 
      log.error("", e); 
      return new ResponseEntity(HttpStatus.BAD_REQUEST); 
     } 
     log.trace("Customer added: " + c.toString()); 
     return new ResponseEntity(c, HttpStatus.CREATED); 
    } 
} 

@RunWith(MockitoJUnitRunner.class) 
@WebMvcTest 
public class CustomerRestTest { 
    private MockMvc mockMvc; 
    @Mock 
    private CustomerService customerService; 
    @Mock 
    private CustomerDao customerDao; 
    @InjectMocks 
    private CustomerController customerController; 

    @Before 
    public void setup(){ 
     this.mockMvc = MockMvcBuilders.standaloneSetup(customerController).build(); 
    } 

    @Test 
    public void testAddDuplicateCustomer() throws Exception { 
     Customer myCustomer = mock(Customer.class); 
     when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class); 
     String content = "{\"lastName\" : \"Orr\",\"firstName\" : \"Richard\",\"userName\" : \"Ricky\"}"; 
     RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/food/customer").accept(MediaType.APPLICATION_JSON). 
       content(content).contentType(MediaType.APPLICATION_JSON); 
     MvcResult result = mockMvc.perform(requestBuilder).andReturn(); 
     MockHttpServletResponse response = result.getResponse(); 
     assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus()); 
    } 
} 

我試圖模仿我的服務層,並將它把我的自定義異常時addCustomer被調用。我回到HttpStatus.CREATED而不是BAD_REQUEST。我可以用服務模擬線(具有thenThrow的線)做不同的工作,它可以正常工作嗎?

回答

1

我認爲這是因爲您期望在when子句內部有一個特定客戶實例,但這種情況從未發生過。 Spring將反序列化您的JSON,並將爲您的方法設置另一個客戶實例。

嘗試修改此:

when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class); 

這樣:

when(customerService.addCustomer(any())).thenThrow(UserNameException.class); 
+0

這做到了!謝謝dzatorsky。 –

相關問題