junit测试无法捕获异常

时间:2020-10-28 01:01:54

标签: spring spring-boot junit

我写了一些测试代码。

首先,我编写了保存数据单元测试。没关系。

第二,我想在保存数据时测试重复的异常。

因此,我保存数据并再次保存相同的数据。 但是我的测试代码失败。

这是我的测试代码。

    @Test
    public void testSaveFail_DuplicateIdHash() throws Exception {
        Map<String, Object> workloadDto = createWorkload(); // created data
        String content = TestUtil.convertObjectToJsonString(workloadDto); // convert map to string
        MvcResult mvcResult = mockMvc.perform(post("/save")
                .content(content)
                .contentType(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andReturn(); // pass 


        
        mvcResult = mockMvc.perform(post("/save")
                .content(content)
                .contentType(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(status().is5xxServerError()) // fail
                .andReturn();
        int responseStatus = mvcResult.getResponse().getStatus();
        logger.info("response:{}", responseStatus);
    }

我的想法写 org.springframework.dao.DuplicateKeyException:

更新数据库时出错。原因:java.sql.SQLIntegrityConstraintViolationException:密钥“ id_hash_UNIQUE”的条目“ itititi”重复

并通过测试。

我不知道如何通过重复的异常测试。

0 个答案:

没有答案