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的線)做不同的工作,它可以正常工作嗎?
這做到了!謝謝dzatorsky。 –