Spring集成Junit4单元测试

1、maven依赖

<properties>
    <org.springframework.version>4.2.4.RELEASEorg.springframework.version>
    <java.version>1.7java.version>
    <maven.compiler.version>3.1maven.compiler.version>
    <junit.version>4.12junit.version>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>

    <dependencies>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${org.springframework.version}version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
    dependencies>

2、注解配置

package com.ricky.codelab.spring;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ricky.codelab.spring.aop.service.HelloService;

/**
 * Spring4 + Junit4集成
 * @author Ricky
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-annotation.xml")
public class HelloServiceTest {

    @Autowired
    private HelloService helloService;

    @Test
    public void testHello(){

        helloService.sayHello("ricky");
    }
}

解释下用到的注解:

  • @RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
  • @ContextConfiguration:用于指定spring配置环境
  • @TransactionConfiguration:用于配置事务
  • @Transactional:表示所有类下所有方法都使用事务


spring-annotation.xml


<beans xmlns="http://www.springframework.org/schema/beans"  
    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:tx="http://www.springframework.org/schema/tx"  
    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/tx  
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  

    <context:annotation-config/>

    <context:component-scan base-package="com.ricky.codelab.spring" />

beans>

你可能感兴趣的:(Spring,Framework)