版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazhen1991/article/details/80692006
在日常的开发中,使用junit测试是必不可少的,下来我们来学习下,在springboot中如何使用junit测试。
- 导入测试所需要的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 编写test类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {StartClass.class})
@WebAppConfiguration
public class SpringbootTest {
@Autowired
private PersonService personService;
@Test
public void testJunitTest(){
System.out.println(personService);
}
}
值得注意的是,类上的第二个注解,在springboot较低的版本中使用的是@SpringApplicationConfiguration(classes = StartClass.class)。
此时,我们就可以编写我们的测试方法了。
在junit中除了使用@Test注解来编写测试案例,还有一些其他的注解,以下为简单介绍:
//测试类初始化方法,在启动时执行,注意,该方法为类方法(static)
@BeforeClass
//测试类的结束方法,一般为容器销毁时执行,也是类方法
@AfterClass
//每个测试方法执行前执行
@Before
//每个方法执行后执行
@After
//不执行的方法
@Ignore