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),即指定启动类。 文章来源:https://www.toymoban.com/news/detail-502140.html
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注解一个静态内部类,在该类中,可以生成需要依赖的组件。文章来源地址https://www.toymoban.com/news/detail-502140.html
到了这里,关于springboot对service方法进行单元测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!