0

SQLException overrideMockedDsConnectionAction在调用case CONNECTEDafter时被抛出case DISCONNECTEDds.getConnection()当期望覆盖以前的行为时,Mockito 调用会引发异常。如何让它发挥作用?

集成测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MyServiceIT {

    @Autowired
    MyService myService;
    
    @SpyBean
    DataSource ds;
    
    private void overrideMockedDsConnectionAction(ACTION overrideWith) throws SQLException {
        switch (overrideWith) {
            case CONNECTED -> given(ds.getConnection()).willCallRealMethod();
            case DISCONNECTED -> given(ds.getConnection()).willThrow(new SQLException("DataSource is DISCONNECTED"));
        }
    }
    
    
    @Test
    public void example() {
    
        try {
            overrideMockedDsConnectionAction(ACTION.DISCONNECTED);
            // call myService method that will use DataSource to persist data
        } catch (SQLException sqlException) {
    
            TimeUnit.SECONDS.sleep(waitTime);
    
            overrideMockedDsConnectionAction(ACTION.CONNECTED);
            log.info("ConnectionState  -> CONNECTED");
        
            // 2nd call of myService method that will use DataSource to persist data
        }
    }
}
4

0 回答 0