实现

在项目的pom/xml中添加测试依赖

SpringBoot整合Junit测试_Test

 

<!-- springBoot整合测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>

 

在controller包下新建要进行测试的controller。

SpringController

package com.example.demo.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class SpringController {
@RequestMapping("/test")
@ResponseBody
public String yes() {
return "test";
}

public static void main(String[] args) {
SpringApplication.run(SpringController.class, args);
}
}

在test包下新建testController

SpringBoot整合Junit测试_Test_02

代码

package com.badao.test;


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;
import org.springframework.test.context.web.WebAppConfiguration;

import com.example.demo.controller.SpringController;

import junit.framework.TestCase;

@SpringBootTest(classes=SpringController.class)//要测试谁
@RunWith(SpringJUnit4ClassRunner.class) //指明进行测试的类
@WebAppConfiguration //指明和Web的整合
public class TestController {

@Autowired
private SpringController springController;

@Test
public void test1() {
TestCase.assertEquals(this.springController.yes(),"test");
}

}

这里使用断言比较返回值是否相等。

右键运行测试类

SpringBoot整合Junit测试_springBoot+Junit_03

可以看到测试结果两个值相等。

SpringBoot整合Junit测试_Test_04