1、pom.xml中引入需要的jar
注:建议spring-Test.jar在pom.xml 文末引入,我在最前面引入报错,说是缺少jar,这点事需要注意的
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version> 3.2.4.RELEASE </version>
<scope>provided</scope>
</dependency>
2、写Junit基类,别的类通过继承此类调用
package com.loan.util;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
//注入bean
@ContextConfiguration("classpath:/application-context.xml")
public class BaseJunit {
}
3、书写测试类
package com.loan.back.controller;
import javax.annotation.Resource;
import org.junit.Test;
import com.loan.security.service.ResourceService;
import com.loan.util.BaseJunit;
public class JunitTest extends BaseJunit{
@Resource
private ResourceService resourceService;
@Test
public void load(){
System.out.println(resourceService.load((long)8).toString());
}
}
4、运行方式
鼠标放置到需运行的方法(load)上,然后右键run as -> JUnit Test即可
Controller测试:
@Controller
@RequestMapping("/admin/resource")
public class ResourceController extends BaseJunit{
@javax.annotation.Resource
private ResourceService resourceService;
@javax.annotation.Resource
private RoleResourceService roleResourceService;
@Test
@RequiresPermissions("resource:view")
@RequestMapping(value="/list", method = RequestMethod.GET)
public void load(){
System.out.println(resourceService.load((long)8).getPic());
}
}
至此,成功!