7

我有一个关于如何最好地处理顶级类的 JUnit 测试的问题。想象一下,我有一个类 SomeWriter,它有一个重新格式化字符串并将其写入流的方法。该方法实际上并不执行工作,而是将其委托给实际执行实际工作的成员对象。我在下面的课程中总结了这一点。

public class SomeWriter {
public void writeReformattedDataToStream(OutputStream outStream, String message) {
        myReformatter.DoTheActualWorkAndWriteDataToStream(outStream, message);
}
}

现在在这个假设的示例中,我已经为 myReformatter 类编写了单元测试,并且我已经证明了 myReformatter 的工作原理。我的问题是,我应该如何处理 SomeWriter 中 writeReformattedDataToStream 的单元测试?

如果我是黑盒测试,我需要编写与应用到 myReformatter 类相同的测试,因为我不知道它是如何实现任务的。但是,单元测试实际上是白盒测试,因此仅确保正确调用 myReformatter 是否有效?

底线是我对 writeReformattedDataToStream 的测试是否应该有效地重复 myReformatter 的测试,或者模拟 myReformatter 并检查它是否被正确调用?

我很欣赏这类似于JUnit 测试 - 类调用其他类中的方法

4

3 回答 3

6

像这样的立即委托通常属于“测试太简单”的标题,但是如果您对它有一些绝对要求,那么您需要模拟您的OutputStream(使用 EasyMock 或类似工具)myReformatter并验证委托是否调用了适当的方法。

于 2013-09-10T08:55:38.033 回答
4

As chrylis says, you should not test this method.

There is actually nothing to test.

If you write a test case that tests that the delegate / service is called, then your test is bound to the implementation of the tested method.

So any change in the implementation of the method would require to change the test; and I am sure that you do not want that.

于 2013-09-10T09:00:19.743 回答
3

尝试注射。出于测试目的,您可以注入自己的 myReformater 类实现,该类只检查该方法是否被正确调用并返回。然后你正在孤立地测试你的测试类。

于 2013-09-10T08:56:54.627 回答