Mockito Spy'ing对被单元测试的物体 [英] Mockito Spy'ing on the object being unit tested

查看:433
本文介绍了Mockito Spy'ing对被单元测试的物体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于正在进行单元测试的物体,间谍是否有异味?例如,假设我有一个 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\nworld");
    }
}

这是否合理?我感觉很漂亮奇怪地测试一个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 Spy'ing对被单元测试的物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆