介紹在Spring的框架下,做
單元測試的兩種辦法。
除了junit4和spring的jar包,還需要spring-test.jar。引入如下依賴:
<span style="font-size:18px;"><span style="white-space:pre"> </span><dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.1.1.RELEASE</version> </dependency></span> |
然后測試類需要繼承自AbstractJUnit4SpringContextTests,這樣就可以在測試類中使用注解簡單的注入需要的bean了。
<span style="font-size:18px;"><span style="color:#ff0000;">@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:applicationContext.xml"})</span> public class ReadDaoImplTest extends<span style="color:#ff0000;"> AbstractJUnit4SpringContextTests</span>{ @Resource ReadDao readDao; @Test public void getListTest(){ List<Client> clientList = readDao.getList("client.test", null); for(Client c:clientList){ System.out.println(c.getVersionNum()); } } } </span> |
二、手動加載spring的配置文件,并啟動spring容器
public class ReadDaoImplTest { public static void main(String[] args){ ClassPathXmlApplicationContext context = <span style="color:#ff0000;">new ClassPathXmlApplicationContext("applicationContext.xml");</span> context.start(); ReadDao fqaService = (ReadDao) context.getBean("readDao"); System.out.println(fqaService); } } |
用這種方式測試,只需要Ctrl+F11就行了