Mockito不会使用REST控制器抛出异常

时间:2016-06-20 11:43:40

标签: java spring-mvc junit mockito

我遇到了REST控制器单元测试的问题(下面给出的代码)。

问题是“testInsertFailure”没有抛出BusinessException,如果我传递“customer”对象,即测试用例失败(java.lang.AssertionError:状态预期:< 400>但是:< 201> )。这是因为它没有到达ControllerAdvice,因为没有抛出异常。

但是,如果我用Mockito.any(Customer.class)替换“customer”对象,那么测试用例可以抛出BusinessException并且它会被PASSED。

但是,对于“testInsertSuccess”测试用例,我不需要这样做(Mockito.any(Customer.class)),它可以直接使用“customer”对象本身。

我的查询是为什么我只需要执行“Mockito.any(Customer.class)”只是为了抛出异常?请您帮助我理解这是如何工作的。

CustomerController类:

import { MOCKEDDATA } from './mocked-data';

CustomerControllerTest Class:

@RestController
@RequestMapping("customers")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @RequestMapping(method = { RequestMethod.POST })
    public ResponseEntity<String> create(@RequestBody Customer customer) {
        customerService.insert(customer);
        return ResponseEntity.status(HttpStatus.CREATED).body("customer created successfully");
    }
}

用于处理例外的CustomerControllerAdvice类: -

@RunWith(MockitoJUnitRunner.class)
public class CustomerControllerTest {

    private MockMvc mockMvc;
    private Customer customer;
    private String customerJSON;

    @Mock
    private CustomerService customerService;

    @InjectMocks
    private CustomerController customerController = new CustomerController();

    @Before
    public void setUp() throws Exception {  
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(customerController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .setControllerAdvice(new CustomerControllerAdvice ()).build();
        customer = new Customer();
        customer.setId(1);
        customer.setName("Sara");
        customerJSON = new ObjectMapper().writeValueAsString(customer);
    }

    @Test
    public void testInsertSuccess() throws Exception {
        Mockito.when(customerService.insertOrUpdate(customer)).thenReturn(customer);
        mockMvc.perform(post("/customers").contentType(MediaType.APPLICATION_JSON).content(customerJSON)
                .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated());
    }

    @Test
    public void testInsertFailure() throws Exception {

        Mockito.when(customerService.insert(customer))
                .thenThrow(new BusinessException("CustomerName", "CustomerName already in use"));

        //If I replace the above line with Mockito.any, the testcase passes
        //Mockito.when(customerService.insert(Mockito.any(Customer.class))
        //      .thenThrow(new BusinessException("CustomerName", "CustomerName already in use"));


        mockMvc.perform(post("/customers").contentType(MediaType.APPLICATION_JSON).content(customerJSON)
                .accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
    }
}

0 个答案:

没有答案