上面的测试中,使用了以下代码来获取容器。
@Before
public void init()
{
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
accountService = (AccountService)applicationContext.getBean("accountService");
System.out.println(accountService);
}
而通过整合Junit,则可以实现自动创建容器。
整合的必要条件
- 归功于junti提供给我们一个注解@RunWith,用以替换运行器。
- Spring容器提供了一个运行器SpringJUnit4ClassRunner,可以读取配置文件或注解来创建容器。
需要使用到的注解
注解 | 功能 |
---|---|
@RunWith | 替换junit原有运行器 |
@ContextConfiguration | 指定Sping的配置文件或者配置类。 locations属性:用于指定配置文件的位置,若在类路径下,需要用classpath:表明;ckasses属性:用于指定注解的类,指定注解类的位置 |
具体操作步骤如下
导入所需jar包的maven座标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
修改测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void testFindAllAccount()
{
List<Account> accounts = accountService.findAllAccount();
for (Account account:accounts)
{
System.out.println(account);
}
}
@Test
public void testFindAccountById()
{
Account account = accountService.findAccountById(1);
System.out.println(account);
}
@Test
public void testSaveAccount()
{
Account account = new Account();
account.setName("灰太狼");
account.setMoney(0.01f);
accountService.saveAccount(account);
}
@Test
public void testUpdateAccount()
{
Account account = accountService.findAccountById(4);
account.setMoney(0.001f);
accountService.updateAccount(account);
}
@Test
public void testDeleteAccount()
{
accountService.deleteAccount(4);
}
}