所以我开始为以下代码安排单元测试:
public interface MyInterface {
void MyInterfaceMethod1();
void MyInterfaceMethod2();
}
public class MyImplementation1 implements MyInterface {
void MyInterfaceMethod1() {
// do something
}
void MyInterfaceMethod2() {
// do something else
}
void SubRoutineP() {
// other functionality specific to this implementation
}
}
public class MyImplementation2 implements MyInterface {
void MyInterfaceMethod1() {
// do a 3rd thing
}
void MyInterfaceMethod2() {
// do something completely different
}
void SubRoutineQ() {
// other functionality specific to this implementation
}
}
有多个实现,并期待更多的实现。
我最初的想法是用这样的东西来节省自己重写单元测试的时间:
public abstract class MyInterfaceTester {
protected MyInterface m_object;
@Setup
public void setUp() {
m_object = getTestedImplementation();
}
public abstract MyInterface getTestedImplementation();
@Test
public void testMyInterfaceMethod1() {
// use m_object to run tests
}
@Test
public void testMyInterfaceMethod2() {
// use m_object to run tests
}
}
然后我可以轻松地对其进行子类化以测试特定于实现的附加方法,如下所示:
public class MyImplementation1Tester extends MyInterfaceTester {
public MyInterface getTestedImplementation() {
return new MyImplementation1();
}
@Test
public void testSubRoutineP() {
// use m_object to run tests
}
}
从实现 2 开始也是如此。
所以我的问题是:有什么理由不这样做吗? JUnit 似乎很喜欢它,它满足了我的需求,但我在阅读的任何单元测试书籍和示例中都没有真正看到过类似的内容。
我是否无意中违反了一些最佳实践?我是否正在为自己的心痛做好准备?有没有我没有考虑过的更好的方法?
感谢您的帮助。
最佳答案
is there any reason not to do this?
没有。做吧。测试是正是这个原因的类。
I haven't really seen anything like it in any of the unit testing books and examples I've been reading.
继续阅读。简介不包括这一点。
Is there some best practice I'm unwittingly violating?
没有。
Am I setting myself up for heartache down the road?
没有。
有些人对“脆弱性测试”感到紧张。您可以在这里找到一些问题,寻找实现它的方法,这样对软件的更改不会同时导致测试发生变化。从长远来看,试图创建“健壮”的测试是愚蠢的。您希望编写测试,以便软件的可见界面级别的每个小更改都需要测试重写。
您需要测试,以便不可见的内部更改不需要测试重写。
类和子类的使用与这些考虑是正交的。
Is there simply a much better way out there I haven't considered?
没有。面向对象是的重点。正是出于这个原因,测试是一个类。
关于java - 单元测试架构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999480/