在JUnit單元測試中獲取bean
阿新 • • 發佈:2019-01-04
一、使用註解@Autowired注入bean
package test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import OThinker.H3.szmc.entities.ZjUsers; import OThinker.H3.szmc.service.EamifService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:./config/applicationContext.xml") public class SolinTest { @Autowired private EamifService es; @Test public void test() { List<ZjUsers> zjUsersList = es.findZjUsersTheDay(); for(ZjUsers zjUsers : zjUsersList) { System.out.println(zjUsers.getUsrCode()+"-------------"+zjUsers.getUsrDesc()); } } }
二、通過ClassPathXmlApplicationContext得到ApplicationContext,再通過getBean獲取bean
(但按照Spring的推薦,在單元測試時不應該依賴於Spring容器,也就是說不應該在單元測試時啟動ApplicationContext並從中獲取Bean,所以此種方法不推薦)
package test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import OThinker.H3.szmc.entities.ZjUsers; import OThinker.H3.szmc.service.EamifService; public class SolinTest { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("./config/applicationContext.xml"); @Test public void test() { EamifService es = (EamifService)applicationContext.getBean(EamifService.class); List<ZjUsers> zjUsersList = es.findZjUsersTheDay(); for(ZjUsers zjUsers : zjUsersList) { System.out.println(zjUsers.getUsrCode()+"-------------"+zjUsers.getUsrDesc()); } } }