Spring Junit数据库连接丢失

时间:2018-06-07 11:33:32

标签: java spring junit4

使用SpringJUnit4ClassRunner在junit中运行多个测试类导致“无法连接到底层数据库”。在@Before注释中,我正在模拟所有bean并在测试方法中使用它。

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore({ "org.apache.logging.log4j.*", "javax.net.ssl.*", "org.apache.http.conn.ssl.*", "javax.crypto.*",
    "javax.management.*" })
@ContextConfiguration(locations = { "classpath:services.xml", "classpath:persistence.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@PrepareForTest({ CommonsUtil.class })
@Transactional

公共类CustomerTest {

// I have loaded all beans required to run this test…. But leading to db connection lost If I run multiple classes like this
@Autowired
CommonService commonSvc;

@Autowired
@Qualifier("registrationService")
RegistrationService registrationSvc;

@Autowired
@Qualifier("paymentProcessor")
PaymentProcessor paymentProcesser;

@Autowired
InquiryCustTxnHandler inquiryCustTxnHandler;

@Before
public void setUp() throws Exception {
    PowerMockito.spy(CommonsUtil.class);
    PowerMockito.doReturn(CommonUtilMock.getApplicationContext()).when(CommonsUtil.class, "getApplicationContext");
    OvoIntegrationProxy ovoIntegrationProxy = Mockito.mock(OvoIntegrationProxy.class);
    ReflectionTestUtils.setField(ovoIntegrationProxy, "ovoHost", "http://localhost:8080/");
    ReflectionTestUtils.setField(commonSvc, "ovoIntegrationProxy", ovoIntegrationProxy);
    ReflectionTestUtils.setField(registrationSvc, "commonService", commonSvc);
    ReflectionTestUtils.setField(paymentProcesser, "registrationService", registrationSvc);
}

@Test
public void inquiryCustomer() throws Exception {
    InquiryCustRequestHelper hlpr = new InquiryCustRequestHelper();
    InquiryCustResp resp = null;
    String xml = hlpr.formInquiryCustRegXml(custreg.getEMoneyId());
    SubmitTransaction transactionRequest = new SubmitTransaction();
    transactionRequest.setRequestXml(xml);
    try {
         BaseTransferObject result = inquiryCustTxnHandler.handleTransaction(transactionRequest);
         resp = hlpr.getUnMarshalled(result.getSpringResponseXml());                        
        } catch (Exception e) {
           e.printStackTrace();
        }
}

}

0 个答案:

没有答案