在测试单元/类中不能使用自动装配

本文阐述了在测试单元或类中避免使用@Autowired的原因,详细解释了测试环境与应用环境的区别,以及如何在SSM和SpringBoot项目中正确配置测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在测试单元/类中不能使用自动装配(@Autowired)

测试类通常采用Junit测试,与tomcat无关,是两个运行环境

如果需要采用注解:
对于SSM,需要加上注解spring配置文件和启动类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/springMVC.xml")

 对于SpringBoot:需要加上注解表明SpringBoot的测试,加上启动类
@SpringBootTest
@RunWith(SpringRunner.class)
### Spring Boot 自动装配测试方法与配置 #### 使用 `@SpringBootTest` 进行集成测试 为了验证自动装配的效果,可以利用 `@SpringBootTest` 注解创建完整的应用程序上下文环境。这允许开发者在一个真实的环境中运行测试案例。 ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class AutoConfigTest { @Autowired private MyService myService; @Test public void testMyService() { String result = myService.sayHello(); System.out.println(result); // 断言或其他验证逻辑 } } ``` 此段代码展示了如何编写基于 `MyService` 的服务层单元测试[^1]。 #### 利用 `@MockBean` 和 `@ImportAutoConfiguration` 当希望模拟某些 Bean 或者仅加载特定部分的自动配置时,可采用 `@MockBean` 来替换真实对象并结合 `@ImportAutoConfiguration` 明确指定要导入哪些自动配置项。 ```java import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods=false) @EnableDiscoveryClient(autoRegister=true) @ImportAutoConfiguration(MyCustomAutoConfiguration.class) class ServiceTests { @MockBean private SomeRepository repository; @BeforeEach void setUp(){ when(repository.findByName(anyString())).thenReturn(Optional.of(new Entity())); } @Test void contextLoads(){} } ``` 上述例子说明了怎样通过自定义配置来控制哪些模块参与到了自动化过程中,并且可以通过 Mock 技术隔离外部依赖[^2]。 #### 编写属性文件覆盖默认设置 有时可能需要调整一些默认行为,在这种情况下可以在项目的资源目录下放置名为 `application.properties` 或 `application.yml` 文件来自定义参数值。 ```yaml # application.yml my.custom.property: value-to-test-with ``` 这些属性将会被用来替代原有预设好的选项,进而影响到整个系统的运作方式[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值