无法模拟服务以使其引发异常



我是使用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 的行(做哪些不同的操作?

我认为这是因为您希望when子句中有一个特定的客户实例,但这从未发生过。Spring 将反序列化您的 JSON,并将为您的方法设置另一个客户实例。

尝试更改以下内容:

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

对此:

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

最新更新