Spring整合Junit

上面的測試中,使用了以下代碼來獲取容器。

    @Before
    public void init()
    {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        accountService = (AccountService)applicationContext.getBean("accountService");
        System.out.println(accountService);
    }

而通過整合Junit,則可以實現自動創建容器。
整合的必要條件

  1. 歸功於junti提供給我們一個註解@RunWith,用以替換運行器。
  2. 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);
    }

}
發佈了71 篇原創文章 · 獲贊 6 · 訪問量 5388
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章