Spring整合Junit4進行單元測試


 

需要添加spring-text.RELEASE.jar。

 

需要添加Junit4的2個jar包:junit.jar、hamcrest-core.jar。

 

 

示例

@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:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM