maven多模块下使用JUnit进行单元测试

1、选中需要进行测试的service类,右键->new->other->JUnit Test Case,如下图:

  

2、编写测试代码如下:

  AppServiceTest.java

import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.servlet.ServletException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import com.lenovo.moc.portal.service.AppService;

/**
 * @author Administrator
 *
 */
@RunWith(JUnit4ClassRunner.class) 
// 由于本测试类位于src/test/java下,而app-context.xml处于src/main/java下,所以需要使用file来获取,
// 否则使用@ContextConfiguration(locations={"classpath:WEB-INF/app-context.xml"})来获取
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-context.xml"})   
public class AppServiceTest{

    private MockHttpServletRequest request;  
    private MockHttpServletResponse response; 
    
    @Autowired
    private AppService appService;
    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        request = new MockHttpServletRequest();      
        request.setCharacterEncoding("UTF-8");      
        response = new MockHttpServletResponse();              
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
    }

    /**
     * Test method for {@link AppService#login(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
     */
    @Test
    public void testAdminAppLogin() {
        
        try {
            request.setParameter("key", "value");
            appService.login(request, response);
            assertEquals(response.getStatus(), 200);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

  JUnit4ClassRunner.java

import java.io.FileNotFoundException;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;

public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {
    static {
        try {
            // 控制台打印日志
            Log4jConfigurer.initLogging("file:src/main/webapp/WEB-INF/log4j.properties");
        } catch (FileNotFoundException ex) {
            System.err.println("Cannot Initialize log4j");
        }
    }
    public JUnit4ClassRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}
View Code

  log4j.properties

log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.stdout.layout.ConversionPattern=- %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${catalina.home}/logs/appTest.log
log4j.appender.logfile.MaxFileSize=512MB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.logger.com.opensymphony.xwork2=ERROR 

# Control logging for other open source packages
log4j.logger.org.springframework=ERROR
log4j.logger.org.quartz=ERROR
log4j.logger.net.sf.ehcache=ERROR
log4j.logger.net.sf.navigator=ERROR
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=ERROR

# Struts OgnlUtil issues unimportant warnings 
log4j.logger.com.opensymphony.xwork2.util.OgnlUtil=error 
log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=error 
View Code

3、maven包:

        <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>        
    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>        
View Code

 

4、右键测试文件进行测试即可。

PS: ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml"); 

    等价于

  @RunWith(SpringJUnit4ClassRunner.class)   @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})  

  

  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 

  等价于

  @RunWith(SpringJUnit4ClassRunner.class)   @ContextConfiguration(locations={"classpath:applicationContext.xml"}) 

 

转载于:https://www.cnblogs.com/siv8/p/6212230.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Maven 进行 springboot 多模块单元测试和 Jacoco 代码覆盖率统计。 对于多模块项目,需要在父 POM 文件中添加 Jacoco 插件配置,以及指定子模块测试目录: ```xml <modules> <module>module1</module> <module>module2</module> <module>module3</module> </modules> <build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.7</version> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report-aggregate</id> <phase>test</phase> <goals> <goal>report-aggregate</goal> </goals> </execution> </executions> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>unit-test</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <configuration> <skipTests>false</skipTests> <skip>false</skip> <forkCount>1</forkCount> <reuseForks>true</reuseForks> <argLine>${jacoco.agent.argLine}</argLine> <excludedGroups>org.junit.experimental.categories.ExcludeCategory</excludedGroups> <testFailureIgnore>true</testFailureIgnore> <includes> <include>**/*Test.java</include> </includes> </configuration> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.6.2</version> </dependency> </dependencies> </plugin> </plugins> </build> </profile> </profiles> <modules> <module>module1</module> <module>module2</module> <module>module3</module> </modules> <profiles> <profile> <id>unit-test</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <configuration> <skipTests>false</skipTests> <skip>false</skip> <forkCount>1</forkCount> <reuseForks>true</reuseForks> <argLine>${jacoco.agent.argLine}</argLine> <excludedGroups>org.junit.experimental.categories.ExcludeCategory</excludedGroups> <testFailureIgnore>true</testFailureIgnore> <includes> <include>**/*Test.java</include> </includes> </configuration> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.6.2</version> </dependency> </dependencies> </plugin> </plugins> </build> </profile> </profiles> ``` 这个配置会在编译和测试时启动 Jacoco 代理,同时在测试后生成 Jacoco 报告。 同时,可以使用 Maven Profiles 来区分测试和生产环境的配置,例如上面的配置中就定义了一个名为 `unit-test` 的 Profile。在执行单元测试时,可以使用命令 `mvn clean test -Punit-test` 来指定使用 `unit-test` Profile。 对于单个模块的项目,可以在模块的 POM 文件中添加 Jacoco 插件配置: ```xml <build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.7</version> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> ``` 这个配置会在编译和测试时启动 Jacoco 代理,同时在测试后生成 Jacoco 报告。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值