SpringBoot整合Junit测试

爱被打了一巴掌 2023-10-18 16:03 259阅读 0赞

场景

相关项目搭建参照:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/column/info/35688

实现

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

![Image 1][]watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70

  1. <!-- springBoot整合测试 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-test</artifactId>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <scope>test</scope>
  11. </dependency>

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

SpringController

  1. package com.example.demo.controller;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. @Controller
  8. @EnableAutoConfiguration
  9. public class SpringController {
  10. @RequestMapping("/test")
  11. @ResponseBody
  12. public String yes() {
  13. return "test";
  14. }
  15. public static void main(String[] args) {
  16. SpringApplication.run(SpringController.class, args);
  17. }
  18. }

在test包下新建testController

![Image 1][]

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 1

代码

  1. package com.badao.test;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7. import org.springframework.test.context.web.WebAppConfiguration;
  8. import com.example.demo.controller.SpringController;
  9. import junit.framework.TestCase;
  10. @SpringBootTest(classes=SpringController.class)//要测试谁
  11. @RunWith(SpringJUnit4ClassRunner.class) //指明进行测试的类
  12. @WebAppConfiguration //指明和Web的整合
  13. public class TestController {
  14. @Autowired
  15. private SpringController springController;
  16. @Test
  17. public void test1() {
  18. TestCase.assertEquals(this.springController.yes(),"test");
  19. }
  20. }

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

右键运行测试类

![Image 1][]

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 2

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

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0JBREFPX0xJVU1BTkdfUUlaSEk_size_16_color_FFFFFF_t_70 3

![Image 1][]

源码下载:

https://download.csdn.net/download/badao_liumang_qizhi/11055983

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读