码迷,mamicode.com
首页 > 编程语言 > 详细

Spring+JUnit4单元测试入门

时间:2017-10-13 21:13:09      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:ota   应用   hand   添加   sed   depend   orm   mave   time   

(一).JUnit介绍

JUnit是Java中最有名的单元测试框架,多数Java的开发环境都已经集成了JUnit作为单元测试的工具。好的单元测试能极大的提高开发效率和代码质量。

Maven导入junit、sprint-test 、json-path相关测试包,并配置maven-suerfire-plugin插件,编辑pom.xml

    <dependencies>
        <!-- Test Unit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.10.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- Json断言测试 -->
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.4.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!-- 单元测试插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit4</artifactId>
                        <version>2.20</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!-- 是否跳过测试 -->
                    <skipTests>false</skipTests>
                    <!-- 排除测试类 -->
                    <excludes>
                        <exclude>**/Base*</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

 

(二).Service层测试示例

创建Service层测试基类,新建BaseServiceTest.java

// 配置Spring中的测试环境
@RunWith(SpringJUnit4ClassRunner.class)
// 指定Spring的配置文件路径
@ContextConfiguration(locations = {"classpath*:/spring/applicationContext.xml"})
// 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
@Transactional(transactionManager = "transactionManager")
// 指定数据库操作不回滚,可选
@Rollback(value = false)
public class BaseServiceTest {
}

 测试UserService类,新建测试类UserServiceTest.java

public class UserServiceTest extends BaseServiceTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class);

    @Resource
    private UserService userService;

    @Test
    public void testGet() {
        UserDO userDO = userService.get(1);

        Assert.assertNotNull(userDO);
        LOGGER.info(userDO.getUsername());

        // 增加验证断言
        Assert.assertEquals("testGet faield", "Google", userDO.getUsername());
    }
}

 

(三).Controller层测试示示例

创建Controller层测试基类,新建BaseControllerTest.java

// 配置Spring中的测试环境
@RunWith(SpringJUnit4ClassRunner.class)
// 指定测试环境使用的ApplicationContext是WebApplicationContext类型的
// value指定web应用的根
@WebAppConfiguration(value = "src/main/webapp")
// 指定Spring容器层次和配置文件路径
@ContextHierarchy({
        @ContextConfiguration(name = "parent", locations = {"classpath*:/spring/applicationContext.xml"}),
        @ContextConfiguration(name = "child", locations = {"classpath*:/spring/applicationContext_mvc.xml"})
})
// 测试类开启事务,需要指定事务管理器,默认测试完成后,数据库操作自动回滚
@Transactional(transactionManager = "transactionManager")
// 指定数据库操作不回滚,可选
@Rollback(value = false)
public class BaseControllerTest {
}

 测试IndexController类,新建测试类IndexControllerTest.java

public class IndexControllerTest extends BaseControllerTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class);

    // 注入webApplicationContext
    @Resource
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    // 初始化mockMvc,在每个测试方法前执行
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
    }

    @Test
    public void testIndex() throws Exception {
        /**
         * mockMvc.perform()执行一个请求
         * get("/server/get")构造一个请求
         * andExpect()添加验证规则
         * andDo()添加一个结果处理器
         * andReturn()执行完成后返回结果
         */
        MvcResult result = mockMvc.perform(get("/server/get")
                .param("id", "1"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Google"))
                .andDo(print())
                .andReturn();

        LOGGER.info(result.getResponse().getContentAsString());

        // 增加验证断言
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }
}

 

(四).执行单元测试

工程测试目录结构如下,运行mvn test命令,自动执行maven-suerfire-plugin插件

技术分享技术分享

执行结果

技术分享

 

(五).BeanCreationNotAllowedException异常

执行测试用例时可能抛BeanCreationNotAllowedException异常

[11 20:47:18,133 WARN ] [Thread-3] (AbstractApplicationContext.java:994) - Exception thrown from ApplicationListener handling ContextClosedEvent
org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name ‘sessionFactory‘: Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:216)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:235)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:192)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)

 通过注入DefaultLifecycleProcessor解决,编辑resources/spring/applicationContext.xml

    <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
        <property name="timeoutPerShutdownPhase" value="10000"/>
    </bean>

Spring+JUnit4单元测试入门

标签:ota   应用   hand   添加   sed   depend   orm   mave   time   

原文地址:http://www.cnblogs.com/faramita2016/p/7637086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!