Spring测试用例自动注入Bean(上)

文章目录
  1. 1. SpringBoot项目 + 注解标识的Bean
  2. 2. Spring + xml配置的Bean
  3. 3. 非SpringBoot + 注解标识的Bean

简单梳理了下有下面三种方法:

SpringBoot项目 + 注解标识的Bean

说明:即在SpringBoot项目中,通过 @Autowired 注入 其他通过 @Component@Service 等注解加入IOC容器里面的Bean。

方法:在Test类前加入以下注解:

1
2
3
4
5
6
@RunWith(SpringRunner.class) 
@SpringBootTest
public class TestServiceTest {
@Autowired
TestService testService;
}

POM依赖如下:

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

Spring + xml配置的Bean

说明:即在test中通过 @Autowired 注入 其他通过 xml配置 加入IOC容器里面的Bean。
方法:在Test类前加入以下注解

1
2
3
4
5
6
@RunWIth(SpringJunit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:xxx.xml"}
public class TestServiceTest {
@Autowired
TestService testService;
}

POM依赖如下:

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>

非SpringBoot + 注解标识的Bean

说明:即在非SpringBoot项目中,通过 @Autowired 注入 其他通过 @Component@Service 等注解加入IOC容器里面的Bean。

可以参考文章:Spring测试用例自动注入Bean(下)