如何在 JUnit 中实例化共享资源
我注意到 jUnit 为每个正在测试的方法运行我的测试类的构造函数。下面是一个示例:
public class TestTest {
protected BigUglyResource bur;
public TestTest(){
bur=new BigUglyResource();
System.out.println("TestTest()");
}
@Test
public void test1(){
System.out.printf("test1()\n");
}
@Test
public void test2(){
System.out.printf("test2()\n");
}
@Test
public void test3(){
System.out.printf("test3()\n");
}
}
给出以下结果:
TestTest() test1() TestTest() test2() TestTest() test3()
调用 BigUglyResource 的构造函数太耗时,我宁愿只构建一次。我知道你可以使用@BeforeClass来运行一个方法一次,但@BeforeClass仅适用于静态方法。静态方法无法访问类属性,如上例中的 BigUglyResource。除了构建单例之外,还有哪些选择?
I noticed that jUnit runs the constructor of my test class for each method being tested. Here's an example:
public class TestTest {
protected BigUglyResource bur;
public TestTest(){
bur=new BigUglyResource();
System.out.println("TestTest()");
}
@Test
public void test1(){
System.out.printf("test1()\n");
}
@Test
public void test2(){
System.out.printf("test2()\n");
}
@Test
public void test3(){
System.out.printf("test3()\n");
}
}
Gives the following result:
TestTest() test1() TestTest() test2() TestTest() test3()
Calling the constructor to BigUglyResource is too time-consuming, I'd prefer to build it only once. I know you can use @BeforeClass to run a method once, but @BeforeClass is only for static methods. Static methods can't access a class property like BigUglyResource in the example above. Other than building a Singleton, what options are there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不能将 BigUglyResource 声明为静态吗?我通常就是这样做的。
Can't you declare the
BigUglyResource
static? This is how I normally do it.您可以使“bur”静态:
并使用@BeforeClass。
You could make "bur" static:
And use @BeforeClass.
对于 JUnit5 用户:您必须使用
@BeforeAll
注释而不是@BeforeEach
,其余部分与 bruno 和 Russ 的答案相同。For JUnit5 users: you have to use
@BeforeAll
annotation instead of@BeforeEach
, the rest stays the same as in bruno's and Russ'es answers.