zoukankan      html  css  js  c++  java
  • 使用maven对项目进行junit的单元测试

    Spring中的单元测试

    需要引入依赖

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
        <scope>test</scope>
    </dependency>
    
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.2.RELEASE</version>
            <scope>test</scope>
    </dependency>
    View Code

    你也可以编写基类,然后具体业务类继承,你也可以直接怼,这里我就规范一下,先写基类

    BaseTest.java如下,其中@Before和@After注解都是junit提供的,其含义写在代码的注释中了:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
    public class BaseTest {
        @Before
        public void init() {
            //在运行测试之前的业务代码
        }
        @After
        public void after() {
            //在测试完成之后的业务代码
        }
    }
    View Code

    编写具体测试类

    写完测试基类后,就可以开始写真正的单元测试了,下面是一个简单的示例:

    public class HelloTest extends BaseTest {
    
        @Test
        public void getTicketInfo() {
            System.out.println("hello");
    }
    View Code

    我们可以看到在IDEA中可以直接对单元测试的某个方法进行运行,不用编译项目和启动服务器就可以达到对业务代码的功能测试,可见其便利程度。

    SpringBoot中的单元测试

    SpringBoot中使用Junit和SpringMVC基本类似,只需要改动一些配置即可。

    加入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test</artifactId>
        <version>1.5.2.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.3.7.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    View Code

    编写测试基类

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BaseTest {
        @Before
        public void init() {
            
        }
        
        @After
        public void after() {
            
        }
    }
    View Code
  • 相关阅读:
    PetShop数据访问层之消息处理 《解剖PetShop》系列之三
    正则过滤汉字
    c语言 断点续传3
    c 写cgi 与socket通信
    C 语言 断点续传2
    承接B2C商城定制开发 空间+域名+风语商城系统=¥4000
    16进制 SQL注入
    c# socket传送大文件
    c写cgi cookies 设置与读取
    cgi 操作封装
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/9060110.html
Copyright © 2011-2022 走看看