无法模拟服务以使其抛出异常

时间:2017-08-05 22:37:51

标签: java spring-mvc spring-boot junit mockito

我是新手使用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 个答案:

答案 0 :(得分:3)

我认为这是因为您希望在when子句中包含特定客户实例,但这种情况永远不会发生。 Spring将反序列化您的JSON,并将另一个客户实例设置为您的方法。

尝试更改此内容:

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

到此:

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