Sprintboot-JUnit

演示环境

SpringBoot 

开发工具:IntelliJ IDEA

Sprintboot-JUnit_第1张图片

1.pom.xml

一般使用idea新建一个SpringBoot web项目时,一般都会自动引入此依赖


    org.springframework.boot
    spring-boot-starter-test
    test

2 UserDAO.cs

package com.example.demo;

import org.springframework.stereotype.Repository;

@Repository
public class UserDAO {
    public void AddUser()
    {
        System.out.print("开始AddUser");

    }
}

3 UserService.cs

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
  private  UserDAO userDAO;
    public void AddUser()
    {
        this.userDAO.AddUser();
    }
}

4测试类

import com.example.demo.DemoApplication;
import com.example.demo.UserService;
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;
/*
@RunWith 启动器
SpringJUnit4ClassRunner 让junit与spring 环境进行整合
@SpringBootTest(classes = DemoApplication.class) 1 当前类为Spring 的测试类  2加载SpringBoot启动类,启动SpringBoot

 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes ={DemoApplication.class})
public class UserServiceText {

    @Autowired
    private UserService userService;

    @Test
    public void textAddUser()
    {
        this.userService.AddUser();

    }
}

结果:

Sprintboot-JUnit_第2张图片

你可能感兴趣的:(SpringBoot)