Spring專門爲Junit testNG提供了一套測試集成接口類——AbstractSpringContextTests類,對於testNG就是其子類:AbstractTestNGSpringContextTests。Spring和testNG整合後,進行單元測試的時只要test類繼承該類,就能夠方便的使用spring注入。實現了spring和testNG的無縫整合,咱們能夠像寫普通類那樣測試被spring IoC容器所管理的類(不然咱們必須在開始執行單元測試前從新加載Spring beanfactory,再用getBean("xxx")的方式獲取IoC容器中類。) 除此之外,對測試類spring beanfactory緩存,使得多個測試類之間能夠共享同一個的beanfactory實例,從而減小了重複生成beanfactory,提升了運行效率。 繼承該類的測試用例在spring管理的事務中進行,測試完後對數據庫的記錄不會形成任何影響。你對數據庫進行一些操做後,它會自動把數據庫回滾,這樣就保證了你的測試對於環境沒有任何影響 集成代碼以下 @ContextConfiguration(locations = {"classpath:spring/spring-mvc.xml"}) public class MyFirstTestNg extends AbstractTestNGSpringContextTests {}package com.bestpay.cif.product.service; import cn.com.bestpay.Response; import com.bestpay.cif.core.enummodel.*; import com.bestpay.cif.product.bizparammodel.CustomerCreateReqDto; import com.bestpay.cif.product.bizparammodel.CustomerCreateResDto; import com.bestpay.cif.product.facade.CustomerProdFacade; import org.junit.Assert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4Cla***unner; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created by laiwenhua on 2015/10/28. */ //@ContextConfiguration(locations = "classpath:spring/spring-mvc.xml") @ContextConfiguration(locations = {"classpath:spring/spring-mvc.xml"}) public class MyFirstTestNg extends AbstractTestNGSpringContextTests { @Autowired private CustomerProdFacade customerService; @BeforeClass public void beforeClass() { System.out.println(customerService+"-----我的開戶測試start---------------"); } @Test public void TestNgLearn() { CustomerCreateReqDto dto = new CustomerCreateReqDto(); dto.setCustomerType(CustomerType.PERSON.getCode()); dto.setLoginName("13600000005"); dto.setBindMobile("13600000005"); dto.setTelecomCompany(TelecomCompany.DX.getCode()); dto.setRegChannel(CustRegChannel.STATIION.getCode()); dto.setDataSourceType(DataSourceType.NORMAL.getCode()); dto.setCertificateType(CertificateType.ID.getCode()); dto.setCertificateNo("22222222222014111304"); dto.setCustomerName("用戶111304"); dto.setLoginType(LoginType.MOBILE.getCode()); dto.setLoginPwd("123456"); dto.setPayPassword("654321"); dto.setCreatedBy("webSys"); dto.setOccupation("IT"); dto.setGender("F"); dto.setEmail("lcd@163.com"); dto.setPostCode("200000"); dto.setHomePhone("66666666"); System.out.println("-------------------"+customerService); Response<CustomerCreateResDto> res = customerService.createPersonCustomer(dto, "createPersonCustomerTest"); System.out.println("createPersonCustomerTest 返回結果:" + res.isSuccess() + " | " + res.getErrorCode() + " | " + res.getErrorMsg()); Assert.assertEquals(true, res.isSuccess()); } @AfterClass public void afterClass() { System.out.println("-----我的開戶測試end---------------"); } }