springboot添加junit测试


pom.xml添加:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
</dependency>

 

文件夹和文件:

 

 

 

类文件:

@SpringBootTest
@RunWith(SpringRunner.class)
//
@RunWith(SpringJUnit4ClassRunner.class)
public class JunitTest {
  @Test
  
public void test1(){
    System.out.println(
"wuewewe");
  }
}

解读:

@SpringBootTest替代了spring-test中的@ContextConfiguration注解,目的是加载ApplicationContext,启动spring容器。如果要引用spring容器总的bean,必须有该注解;不涉及可以不加该注解。

@RunWith是Junit4提供的注解,将Spring和Junit链接了起来。假如使用Junit5,不再需要使用@ExtendWith注解,@SpringBootTest和其它@*Test默认已经包含了该注解。

@RunWith(SpringRunner.class)

@RunWith(SpringJUnit4ClassRunner.class)

这两个有什么区别?

SpringRunner 继承了SpringJUnit4ClassRunner,没有扩展任何功能;使用前者,名字简短而已。

源码:

package org.springframework.test.context.junit4;

import org.junit.runners.model.InitializationError;

public final class SpringRunner extends SpringJUnit4ClassRunner {
    public SpringRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM