junit强制在方法调用时引发异常

xzv2uavs  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(365)

我试图在任何时候抛出异常 simpleJdbcCall.execute(namedParameters) 但我看到它没有抛出错误,是不是有什么我在这里错过了?
这是我的课

class A {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private SimpleJdbcCall simpleJdbcCall;

    public int mymeth(){
         simpleJdbcCall.withProcedureName("myproc").declareParameters(new SqlParameter("ID", 
         Types.VARCHAR);
         SqlParameterSource namedParameters = new MapSqlParameterSource("id" , 12);
         Map<String, Object> result = null;
         try {
            //I want Junit to throw error here
            result = simpleJdbcCall.execute(namedParameters);

          } catch (Exception e) {

           throw new Exception(e.getMessage());
          }
 return (Integer) result.get("Status");
     }

}

这是我的初中班

@RunWith(SpringRunner.class)

@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
Class ATest{

  @Autowired
  private A obj;

  @Test
    public void throwExceptionFromMethod() {

        try {
            SimpleJdbcCall simpleJdbcCall = Mockito.mock(SimpleJdbcCall.class);
            SqlParameterSource sqlParameterSource = Mockito.mock(SqlParameterSource.class);

            Mockito.doThrow(new RuntimeException()).when(simpleJdbcCall ).execute((Object) 
            Mockito.any());
            final int message = obj.mymeth(modifyLeadDispositionRequest);
            Assert.assertEquals(0, message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
bt1cpqcv

bt1cpqcv1#

在编写springboot集成测试时,应该使用@mockbean注解注入模拟bean

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
Class ATest {

    @Autowired
    private A obj;

    @MockBean
    private SimpleJdbcCall simpleJdbcCall;

    @Test
    public void throwExceptionFromMethod() {

    try {

        Mockito.when(simpleJdbcCall.withProcedureName(Mockito.anyString())).thenReturn(simpleJdbcCall);
        Mockito.when(simpleJdbcCall.declareParameters(Mockito.any())).thenReturn(simpleJdbcCall);
        Mockito.doThrow(new RuntimeException()).when(simpleJdbcCall).execute( 
        ArgumentMatchers.any(SqlParameterSource.class)); 

        //or you can use thenThrow also

        Mockito.when(simpleJdbcCall.execute(ArgumentMatchers.any(SqlParameterSource.class))).thenThrow(RuntimeException.class);

        final int message = obj.mymeth(modifyLeadDispositionRequest);

    } catch (Exception e) {
        e.printStackTrace();
       // just to assert here 
    }
  }
}

您可以按照这里的一些示例来测试junit4或junit5中的异常

相关问题