maven工程中,src目录同级别下的test文件,我们用于做单元测试,这样保存测试代码以后进行代码调试或者代码验证是很方便的,一般来说我们工程结构如下
其中配置文件都在resources目录下,测试代码都存放于test目录下
我们需要在test中做基于spring的测试代码需要做以下操作
在junit文件头部加上如下代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
@Transactional
第一行告诉junit需要使用SpringJUnit4ClassRunner.class才能做基于junit的测试
第二行告知spring配置文件所在的位置
第三行启用spring的注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
@Transactional
public class UserServiceImplTest {
@Resource(name="userService")
private UserService service;
@Test
public void testGetUserByName() {
//do somthing...
service.authentication(User user);
}
}
这样就可以完成测试工作了