Spring对junit的整合

Spring对junit的整合

 1 package cn.mepu.service;
 2 
 3 import cn.mepu.config.SpringConfiguration;
 4 import cn.mepu.domain.Account;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import java.util.List;
12 
13 /**
14  * @author shkstart
15  * @create 2019-11-08 10:45
16  * junit的整合:
17  *  junit不会关注我们是否使用Spring框架,所以加了@Autowired注解也不能注入
18  *  说明测试方法执行时没有ioc容器
19  *      方法:换了junit的main方法在pom中导入spring-test
20  *      使用junit提供的@Runwith注解把main方法替换为spring提供的传入字节码
21  *      告知spring的运行器spring和ioc是基于注解还是xml,说明位置
22  *          @ContextConfiguration
23  *              locations=xml的位置加classpath关键字表示类路径下
24  *              classes=指定注解位置
25  *      当使用spring5.x版本时,junit的jar包必须是4.1.2及以上
26  */
27 @RunWith(SpringJUnit4ClassRunner.class)
28 @ContextConfiguration(classes = SpringConfiguration.class)
29 public class AccountServiceTest {
30 
31     @Autowired
32     private AccountService service;
33 
34 
35     @Test
36     public void testFindAll(){
37     //3.执行方法
38         List<Account> accounts = service.findAllAccount();
39         for (Account account : accounts) {
40             System.out.println("account = " + account);
41         }
42 
43     }
44 
45     @Test
46     public void testFindOne(){
47         //3.执行方法
48         Account account = service.findAccountById(1);
49         System.out.println(account);
50     }
51 
52     @Test
53     public void testSave(){
54         //3.执行方法
55         service.saveAccount(new Account(1,"DDD",1234));
56     }
57 
58     @Test
59     public void testUpdate(){
60         //3.执行方法
61         service.updateAccount(new Account(1,"DDD",2345));
62     }
63 
64     @Test
65     public void testDelete(){
66 
67         //3.执行方法
68         service.deleteAccount(4);
69     }
70 }

猜你喜欢

转载自www.cnblogs.com/aikang525/p/11820652.html