需要添加spring-text.RELEASE.jar。
需要添加Junit4的2個jar包:junit.jar、hamcrest-core.jar。
- 寫Junit的注解,Alt+Enter添加即可。
- 也可以自己下載添加:https://github.com/junit-team/junit4/wiki/Download-and-Install
示例
@RunWith(SpringJUnit4ClassRunner.class) //值是String數組,可以寫多個xml配置文件 @ContextConfiguration(locations = {"classpath:spring-config.xml"}) public class Test { @Autowired private User user; @org.junit.Test public void test1(){ System.out.println(user); } @org.junit.Test public void test2(){ System.out.println(user); } @org.junit.Test public void test3(){ System.out.println(user); } }
在測試類上標注:
-
@RunWith 會自動根據配置創建Spring容器,無需 new ClassPathXmlApplicationContext("spring-config.xml") 手動創建
- @ContextConfiguration 指定xml配置文件的路徑
在測試方法上標注:
- @Test
可添加前后處理:
@Before public void before(){ System.out.println("before"); } @After public void after(){ System.out.println("after"); }
run/debug時使用Junit: