Spring5(7)- spring 整合 junit

1 spring 整合 junit

  1. 導入 spring 整合 junit 的 jar
 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring-version}</version>
    </dependency>
  1. 使用 Junit 註解把原有的 main 方法替換成 spring 提供的,@RunWith
  2. 告訴 spring 運行器,IOC 創建是基於 xml 還是 註解,並且說明位置
    @ContextConfiguration
    屬性:
    (1) locations:指定 xml 文件的位置,加上 classpath
    (2)classes : 指定配置類字節碼

2 單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

   @Autowired
    private IAccountService as;

    @Test
    public void testFindAll() {
        List<Account> accounts = as.findAllAccount();
        System.out.println(accounts);
    }

    @Test
    public void testFindOne() {
        // 獲取容器
        //ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

        IAccountService as = ac.getBean("accountService", AccountServiceImpl.class);

        Account account = as.findAccountById(1);
        System.out.println(account);
    }

  
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章