当前位置:   article > 正文

springboot对service方法进行单元测试_springboot单元测试service

springboot单元测试service

1. 在pom.xml文件添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>

2. service类

这里为了简化,没有将接口和实现单独定义。

  1. package com.demo.order.service;
  2. import org.springframework.stereotype.Service;
  3. /**
  4. *
  5. */
  6. @Service
  7. public class OrderService {
  8. public String getOrder()
  9. {
  10. return "123456789";
  11. }
  12. }

3. 测试类

  1. package com.demo.order.service;
  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.SpringRunner;
  7. /**
  8. *
  9. */
  10. @RunWith(SpringRunner.class)
  11. @SpringBootTest
  12. public class OrderServiceTest {
  13. @Autowired
  14. private OrderService orderService;
  15. @Test
  16. public void getOrderTest()
  17. {
  18. String order = orderService.getOrder();
  19. System.out.println("orderNo = " + order);
  20. }
  21. }

@SpringBootTest注解会将springboot程序完整的运行起来。还可以写成@SpringBootTest(classes = OrderApplication.class),即指定启动类。 

4. 执行测试

  1. 2022-01-10 10:52:01.137 INFO 33168 --- [ main] c.demo.order.service.OrderServiceTest : Started OrderServiceTest in 2.148 seconds (JVM running for 3.004)
  2. orderNo = 123456789
  3. 2022-01-10 10:52:01.297 INFO 33168 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

5. 除了启动整个应用以外,还可以只加载需要的组件进行单元测试

  1. package com.demo.order.service;
  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.boot.test.context.TestConfiguration;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. /**
  10. *
  11. */
  12. @RunWith(SpringRunner.class)
  13. public class OrderService2Test {
  14. @TestConfiguration
  15. static class prepareOrderService{
  16. @Bean
  17. public OrderService getOrderService() {
  18. return new OrderService();
  19. }
  20. }
  21. @Autowired
  22. private OrderService orderService;
  23. @Test
  24. public void getOrderTest()
  25. {
  26. String order = orderService.getOrder();
  27. System.out.println("orderNo = " + order);
  28. }
  29. }

这里不使用@SpringBootTest注解,而是使用@TestConfiguration注解一个静态内部类,在该类中,可以生成需要依赖的组件。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/653871
推荐阅读
相关标签
  

闽ICP备14008679号