监视正在单元测试的对象是否是代码异味?例如,假设我有一个 LineCounter
类,其工作是简单地计算字符串中的行数.--
Is it a code smell to spy on an object that is being unit tested? For example say I have a LineCounter
class whose job is to simply count the number of lines in a string. --
class LineCounter {
public int getNumLines(String string) {
String metadata = getStringMetadata(string);
// count lines in file
return numLines;
}
/** Expensive operation */
protected String getStringMetadata(String string) {
// do stuff with string
}
}
现在我想为此编写一个 JUnit 4 测试来测试 getNumLines
方法,同时模拟昂贵的 getStringMetadata
调用.我决定使用 Mockito 的间谍机制让 getStringMetadata
返回一个虚拟值.
Now I want to write a JUnit 4 test for this to test the getNumLines
method while mocking out the expensive getStringMetadata
call. I decide to use Mockito's spy mechanism to have getStringMetadata
return a dummy value.
class LineCounterTests {
@Test public void testGetNumLines() {
LineCounter lineCounterSpy = Mockito.spy(new LineCounter());
// Mock out expensive call to return dummy value.
Mockito.when(lineCounterSpy.getStringMetadata(Mockito.anyString()).thenReturn("foo");
assertEquals(2, lineCounterSpy.getNumLines("hello
world");
}
}
这是合理的做法吗?我觉得测试一个 Spy 对象而不是实际的类很奇怪,但我真的想不出反对它的理由.
Is this a reasonable thing to do? I feel pretty weird testing a Spy object rather than the actual class, but I can't really think of a reason against it.
我将分两部分回答这个问题.首先,是的,模拟或监视被测类是代码异味.这并不意味着它不能正确完成,而是它容易发生风险,应尽可能避免.
I will answer the question in two parts. First, yes it is code smell to mock or spy the class under test. That does not mean that it cannot be done correctly but that it is risk prone and should be avoided whenever possible.
WRT 你的具体例子,我会看看如何正确使用间谍,但这将取决于你在其他地方已经完全单元测试的断言 getStringMetadata
.这就引出了一个问题,如果您在其他地方对 getStringMetadata
进行了完整的单元测试,那么您必须知道如何测试它,因此为什么不测试 getNumLines
没有间谍.
WRT your specific example, I would see how the spy could be correctly used but that would be predicated on the assertion that you have elsewhere fully unit tested getStringMetadata
. This then begs the question, if you have fully unit tested getStringMetadata
elsewhere then you must know how to test it and therefore why not test getNumLines
without the spy.
话虽如此,millhouse
提出了一个很好的观点,但无论哪种方式,您都必须在某处对昂贵的代码进行单元测试.他的建议有助于隔离昂贵的代码并确保您只需测试/练习一次.
All this being said, millhouse
makes a good point but either way you have to unit test the expensive code somewhere. His suggestion goes a long way to help isolate the expensive code and ensure that you only have to test / exercise it once.
这篇关于Mockito 监视正在单元测试的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!