SpringBoot: 16.整合junit单元测试(转)

 

1、创建maven项目,修改pom.xml文件

复制代码
<!--springboot项目依赖的父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <!--注入springboot启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--添加junit环境的jar包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
复制代码

2、dao层代码

复制代码
package com.bjsxt.dao;

import org.springframework.stereotype.Repository;

/**
 * Created by Administrator on 2019/2/14.
 */
@Repository
public class UserDaoImpl {

    public void saveUser(){
        System.out.print("insert into user...");
    }
}
复制代码

3、service层代码

复制代码
package com.bjsxt.service;

import com.bjsxt.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2019/2/14.
 */
@Service
public class UserServiceImpl {

    @Autowired
    private UserDaoImpl userDaoImpl;


    public void saveUser(){
        userDaoImpl.saveUser();
    }

}
复制代码

4、编写启动类

复制代码
package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by Administrator on 2019/2/14.
 */
@SpringBootApplication
public class App {

    public static void main(String[] args){
        SpringApplication.run(App.class,args);
    }
}
复制代码

5、编写测试文件,运行testSaveUser方法即可

复制代码
package com.bjsxt.test;

/**
 * Created by Administrator on 2019/2/14.
 */

import com.bjsxt.App;
import com.bjsxt.service.UserServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * SpringBoot 测试类
 *
 * @RunWith:启动器 SpringJUnit4ClassRunner.class:让 junit 与 spring 环境进行整合
 * @SpringBootTest(classes={App.class}) 1, 当前类为 springBoot 的测试类
 * @SpringBootTest(classes={App.class}) 2, 加载 SpringBoot 启动类。启动springBoot
 * junit 与 spring 整合@Contextconfiguartion("classpath:applicationContext.xml")
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {App.class})
public class UserServiceTest {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Test
    public void testSaveUser(){
        userServiceImpl.saveUser();
    }

}
复制代码

6、目录结构

posted @ 2019-02-24 18:35  咫尺天涯是路人丶  阅读(261)  评论(0编辑  收藏  举报