• 使用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
  • 相关阅读:
    zencart_magiczoom
    如何把一个TXT文本文件按行数分割成多个文本文件
    工作时常用东西汇总
    asp Vernum
    sitemap制作
    php后门屌炸天
    威盾解密
    软路由
    企业安全工作要点
    内网ARP攻击
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/9060110.html
Copyright © 2020-2023  润新知