集成Junit

在demo-service層集成junit並實例測試。java

1.demo-service中pom.xml

引入spring-test,junit中jarspring

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.2.3.RELEASE</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

 

2.demo-service中test目錄

  • BaseJunitTest:全部測試類基類,主要是加載其對應的配置文件

classpath*:表示加載其餘jar中配置文件(即demo-data中mybatis相關配置)。express

package base;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:spring-*.xml",
        "classpath*:mybatis/mybatis-*.xml"})
public class BaseJunitTest {

}
  • resources目錄建立後將其設置成test-resources

  • spring-service.xml:用於掃描@Service註解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        ">

        <!--spring ioc中掃描-註解Service掃入-->
        <context:component-scan base-package="com.company">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        </context:component-scan>

</beans>
  • UserServiceTest:測試代碼
package service;

import base.BaseJunitTest;
import com.company.data.model.User;
import com.company.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;


public class UserServiceTest extends BaseJunitTest {
    @Autowired
    private UserService userService;

    @Test
    public void  test(){
        User user = userService.qryUserById(1L);
        Assert.assertTrue(user != null);
    }
}

 

3.Junit測試

1)執行

在要執行方法體上,鼠標右擊選擇Runspring-mvc

2)執行結果說明

  • 執行成功而且斷言也成功:綠色

  • 執行成功,但斷言失敗: 橙色

  • 執行失敗:紅色

相關文章
相關標籤/搜索