JUnit @BeforeClass用于Spring Boot应用程序的非静态解决方法 [英] JUnit @BeforeClass non-static work around for Spring Boot application

查看:262
本文介绍了JUnit @BeforeClass用于Spring Boot应用程序的非静态解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JUnit的@BeforeClass批注在所有@Test方法之前运行一次,则必须将其声明为静态.但是,这不能与依赖项注入一起使用.

JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.

我想在运行JUnit测试之前使用Spring Boot清理我@Autowire的数据库.我不能@Autowire静态字段,所以我需要考虑一种解决方法.有什么想法吗?

I want to clean up a database that I @Autowire with Spring Boot, once before I run my JUnit tests. I cannot @Autowire static fields so I need to think of a work around. Any ideas?

推荐答案

只需使用@Before(而不是@BeforeClass)(或BeforeTransaction(取决于初始化数据库的方式)).该注释必须附加到非静态公共方法上.

Just use @Before (instead of @BeforeClass) (or BeforeTransaction (depending on how you initialize the database)). This annotation must been attached to an nonstatic public method.

当然:@Before在每个测试用例方法之前运行(与仅运行一次的@BeforeClass不同).但是,如果要恰好运行一次,请使用静态标记字段.

Of course: @Before run before EACH test case method (not like @BeforeClass that runs only once.) But if you want to run it exactly once, then use an static marker field.

private static boolean initialized = false;
...
@Before
public void initializeDB() { 
   if (!initialized) {
       ... //your db initialization
       initialized = true;
   }
}
---

这篇关于JUnit @BeforeClass用于Spring Boot应用程序的非静态解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆