赞
踩
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
这里为了简化,没有将接口和实现单独定义。
- package com.demo.order.service;
-
- import org.springframework.stereotype.Service;
-
- /**
- *
- */
- @Service
- public class OrderService {
-
- public String getOrder()
- {
- return "123456789";
- }
- }
- package com.demo.order.service;
-
- 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.SpringRunner;
-
- /**
- *
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class OrderServiceTest {
-
- @Autowired
- private OrderService orderService;
-
- @Test
- public void getOrderTest()
- {
- String order = orderService.getOrder();
- System.out.println("orderNo = " + order);
- }
-
- }
@SpringBootTest注解会将springboot程序完整的运行起来。还可以写成@SpringBootTest(classes = OrderApplication.class),即指定启动类。
- 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)
- orderNo = 123456789
- 2022-01-10 10:52:01.297 INFO 33168 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
- package com.demo.order.service;
-
- 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.boot.test.context.TestConfiguration;
- import org.springframework.context.annotation.Bean;
- import org.springframework.test.context.junit4.SpringRunner;
-
- /**
- *
- */
- @RunWith(SpringRunner.class)
- public class OrderService2Test {
-
- @TestConfiguration
- static class prepareOrderService{
- @Bean
- public OrderService getOrderService() {
- return new OrderService();
- }
- }
-
- @Autowired
- private OrderService orderService;
-
- @Test
- public void getOrderTest()
- {
- String order = orderService.getOrder();
- System.out.println("orderNo = " + order);
- }
-
- }
这里不使用@SpringBootTest注解,而是使用@TestConfiguration注解一个静态内部类,在该类中,可以生成需要依赖的组件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。