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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2. service类

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

package com.demo.order.service;

import org.springframework.stereotype.Service;

/**
 * 
 */
@Service
public class OrderService {

    public String getOrder()
    {
        return "123456789";
    }
}

3. 测试类

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),即指定启动类。 

4. 执行测试

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'

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

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注解一个静态内部类,在该类中,可以生成需要依赖的组件。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐