JUnit 扩展基类并在该类中运行测试
我正在使用 JUnit 3,并且经常遇到这样的情况:我必须测试对象是否已正确创建。我的想法是编写一个类 MyTestBase
,如下所示,然后从该类扩展以进行特定情况的单元测试。
但是,在我给出的示例中,MyTests
不会运行 MyTestBase
中的测试。
public class MyTestBase extends TestCase {
protected String foo;
public void testFooNotNull() {
assertNotNull(foo);
}
public void testFooValue() {
assertEquals("bar", foo);
}
}
public class MyTests extends MyTestBase {
public void setUp() {
this.foo = "bar";
}
public void testSomethingElse() {
assertTrue(true);
}
}
我做错了什么?
更新抱歉。愚蠢的错误。我的基类中的测试未正确命名。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您说过“MyTests 不运行 MyTestBase 中的测试。”。我尝试了一下,所有测试都被调用,包括 MyTestBase 中的测试。
You have said "MyTests does not run the tests in MyTestBase.". I tried it and all tests were called including the ones in MyTestBase.
好吧,您可以将
MyTestBase
抽象化,这样它就不会尝试在基类中运行测试。更好的解决方案是在基类中使用setUp
并使其调用抽象方法(例如getFoo()
)来初始化稍后需要的变量。事实上,如果您有这些抽象方法,您可能会发现您甚至不需要首先设置阶段 - 您可以在需要值的地方调用抽象方法,而不是使用实例变量。显然,这取决于具体情况,但在许多情况下,这可能会更干净。
Well, you could make
MyTestBase
abstract, so that it didn't try to run tests in the base class. A better solution would be to havesetUp
in the base class and make it call abstract methods (e.g.getFoo()
) to initialize the variables it will require later on.In fact, if you have those abstract methods you may find you don't even need a set-up phase in the first place - you could call the abstract methods where you need the value, instead of using an instance variable. Obviously it will depend on the exact situation, but in many cases this could be a lot cleaner.
您尝试做的并不是实现目标的最合适方法:
如果您希望拥有一些通用功能,使某些检查
static
方法What you are trying to do is not the most appropriate way to achieve your goal:
If you want to have common functionality that makes some checks
static
methods我不知道你到底想做什么,但通常在测试中使用太多公共部分并不是一个好主意,因为当公共部分失败时,你将有大量的测试失败,甚至你可能有只是您软件中的一个小错误。
我建议您使用 Factory 或 Builder 来创建复杂的对象,然后测试 Factory(或 Builder)是否正确创建对象。
I don't know what exactly you want to do, but usually it is not a very good idea to too much common parts in test, because when the common part fails you will have a large number of tests that fail even tough you probably have just one small bug in your software.
I suggest you to use a Factory or a Builder to create the complex object and then test the Factory (or Builder) for creating the object correctly.