【Spring】Spring和JUnit5整合及注解


Spring和JUnit5整合及注解

  • 原寫法:

    需要手寫代碼,根據配置文件加載上下文,從而得到bean,調用方法。

    public class MyTest2 {
    
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            TutorService tutorService = context.getBean("tutorServiceImpl", TutorService.class);
            Tutor tutor = tutorService.getTutorById("20170000");
            System.out.println(tutor);
        }
    
    }
    

可以使用注解簡化

  • 加入依賴:spring-test的版本和spring要一致。

    		<dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter</artifactId>
                <version>RELEASE</version>
                <scope>test</scope>
            </dependency>
            <!--spring-test-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.2.12.RELEASE</version>
                <scope>test</scope>
            </dependency>
    
  • 使用注解的測試類

    JUnit5使用@ExtendWith(SpringExtension.class)

    *@ExtendWith和@ContextConfiguration可以合並,寫復合注解@SpringJUnitConfig(locations="classpath:applicationContext.xml")

    import org.junit.jupiter.api.Test;//保證這個包導入
    
    @ExtendWith(SpringExtension.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class MyTest {
    
        @Autowired
        TutorService tutorService;
    
        @Test
        public void test2() {
            Tutor tutor = tutorService.getTutorById("20170000");
            System.out.println("tutor=" + tutor);
        }
    }
    

    *JUnit4使用@Runwith(SpringJUnit4ClassRunner.class)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM