Junit Force 在方法调用时抛出异常

Junit Force to throw Exception on method call

每当调用 simpleJdbcCall.execute(namedParameters) 时,我都试图抛出异常,但我发现它没有抛出错误,我在这里遗漏了什么吗?

这是我的class

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");
     }

}

这是我的 Junit Class


@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();
        }
    }
}

编写 spring-boot 集成测试时,您应该使用 @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 or junit5

中的异常