JUnit 4 创建测试用例以使用通用功能的正确方法是什么:例如,几个单元测试类通用的设置?我所做的是创建一个测试用例并将通用功能放入 @Before
方法中,然后任何需要此功能的测试用例都会扩展基类。然而,这似乎需要在每个子类中执行: super.setUp()
。
有更好的办法吗?
编辑
实际上我提出的解决方案不起作用。有时 JUnit 会调用基类两次。如果碰巧首先在基类上运行测试,则一次,当它到达子类时再次运行测试(至少我认为这是正在发生的事情)。因此,“继承”通用测试用例功能的更好方法会很棒。
What is the proper way with JUnit 4 to create test cases to use common functionality: e.g. setup that is common to several unit test classes? What I did was create a test case and put the common functionality in the @Before
method, then any test case that needs this would extend the base class. However, this seems to require doing: super.setUp()
in every subclass.
Is there a better way?
EDIT
Actually my proposed solution is not working. Sometimes JUnit will call the base class TWICE. Once if it happens to run the test on the base class first, and again when it reaches a child class (at least I think this is whats happening). So a better way of "inheriting" common test case functionality would be great.
发布评论
评论(4)
如果您使用 super.setup() “nofollow">
@Before
注释:我建议这样:
在超级/主类
和任何
测试用例中。
编辑:
在编辑中回答您的问题。
@BeforeClass
,每个 TestClass 都会调用一次。我这样做:
You don't need to invoker
super.setup()
if you use the@Before
annotation:I'd suggest something like this:
In the super/Main class
and any
In your Testcases.
EDIT:
To answer your questions in the edit.
@BeforeClass
which will be invoked once per TestClass.I do this like this:
这是一个非常好的方法。如果子类上有
setUp()
,那么是的,您必须调用super.setUp()
,但实际上,这有多难?thats a pretty good way to do it. If you have a
setUp()
on the subclass, then yes, you have to invokesuper.setUp()
, but really, how hard is that?您是否尝试过其他方法。
不要创建具有公共功能的基类,而是创建一个具有公共功能的静态方法的 util 类。然后只需在每个测试用例的@Before注释方法中调用util方法即可。
Have you tried other approach.
Instead of creating a base class with a common functionality, make an util class with static methods which will the common functionality. Then just call util methods in @Before annotated method of each test case.
如果您的基类有一个方法 public void setUp(),您的子类也有一个方法 public void setUp(),那么子类的 setUp 方法覆盖基类的同名和签名的方法,因此只有子类的方法将被调用(并且它可能在应该调用基类的方法时被调用;对此不确定)。
解决方案是调用您的基类设置方法,例如baseSetup()。然后它们都会被自动调用。 Joachim 的答案确实解决了命名问题,但我想更清楚地了解方法重写的效果。
If your base class has a method public void setUp(), and so does your sub-class, then the sub-class's setUp method overrides the base class's method of the same name and signature, so only the sub-class's method will be called (and it may be called when the base class's method should have been called; not sure about this).
The solution is to call your base class setup method something else, e.g. baseSetup(). Then they will both be called automatically. Joachim's answer does address the naming, but I wanted to be clearer about the effects of method override.