这里有三个方法可以使用:(如有雷同肯定是抄的我的。。。不过本人大方,不追求版权问题)
这里需要引入Junit4、spring-test两个jar文件
pom文件如下:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.4.RELEASE</version> </dependency>
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:applicationContext.xml"}) public class TestUserDao extends AbstractJUnit4SpringContextTests { @Resource private UserDao userDao; @Test public void testUserSave(){ System.out.println(userDao); } }
让测试类继承:AbstractTransactionalJUnit4SpringContextTests这个类
@ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class TestUserServiceAbstractTransactionalJUnit4SpringContextTests extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private UserService userService; @Test public void handleUserLogin(){ System.out.println(userService); } }这个其实和上面方法一差不多,这个 AbstractTransactionalJUnit4SpringContextTests是继承了方法一里面的
运行结果:
注意:这里需要在spring配置文件也就是上面applicationContext.xml制定一个dataSource,因为在AbstractTransactionalJUnit4SpringContextTests里面需要指定dataSource,如下图:
ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); context.start(); UserDao userDao = (UserDao) context.getBean("userDao"); System.out.println(userDao);