首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计数间接方法调用Mockito

计数间接方法调用Mockito
EN

Stack Overflow用户
提问于 2011-10-20 08:00:09
回答 4查看 13.1K关注 0票数 8

我在计算Mockito的方法调用时遇到了问题。问题是,调用我想要计数的方法在test类中被其他方法间接调用。代码如下:

代码语言:javascript
运行
复制
public class ClassForTest {
    private Integer value;

    public void doSmth() {
        prepareValue("First call");
        prepareValue("Second call");
        prepareValue("Third call");
        System.out.println(value);
    }

    protected void prepareValue(String msg) {
        System.out.println("This is message: " + msg);
        value++;
    }
}

以及测试类:

代码语言:javascript
运行
复制
public class ClassForTestTest extends TestCase {
    @Test
    public void testDoSmth() {
        ClassForTest testMock = mock(ClassForTest.class);
        doNothing().when(testMock).prepareValue(anyString());
        testMock.doSmth();
        verify(testMock, times(3)).prepareValue(anyString());
    }
}

有这样的例外:

代码语言:javascript
运行
复制
Wanted but not invoked:
classForTest.prepareValue(<any>);
-> at org.testing.ClassForTestTest.testDoSmth(ClassForTestTest.java:24)

However, there were other interactions with this mock:
-> at org.testing.ClassForTestTest.testDoSmth(ClassForTestTest.java:21)

有什么想法请告诉我。提前感谢!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-10-20 10:39:30

这将会起作用。使用spy调用底层方法。确保先初始化value

代码语言:javascript
运行
复制
    @Test
    public void testDoSmth() {
        ClassForTest testMock = spy(new ClassForTest());
        testMock.doSmth();
        verify(testMock, times(3)).prepareValue(anyString());
    }

    public class ClassForTest {
        private Integer value = 0;

        public void doSmth() {
            prepareValue("First call");
            prepareValue("Second call");
            prepareValue("Third call");
            System.out.println(value);
        }

        protected void prepareValue(String msg) {
            System.out.println("This is message: " + msg);
            value++;
        }
    }
票数 12
EN

Stack Overflow用户

发布于 2011-10-20 11:33:28

这表明你需要一些重构来改进你的设计。一个单独的类应该是完全可测试的,而不需要模拟它的各个部分。您认为需要模拟的任何部分都应该提取到一个或多个协作对象中。‘t落入部分模仿的陷阱。听一听测试告诉你什么。你未来的自己会感谢你的。

票数 5
EN

Stack Overflow用户

发布于 2011-10-20 09:47:17

你在嘲笑被测试的类。Mocking用于测试类的依赖项,而不是类本身。

我怀疑你想要的是Mockito.spy()。然而,这是Mockito Javadoc建议反对的部分模拟。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7829659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档