如何告诉 Mockito 模拟对象在下次调用时返回不同的东西?

时间:2022-11-01
本文介绍了如何告诉 Mockito 模拟对象在下次调用时返回不同的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

所以,我在类级别创建一个模拟对象作为静态变量,就像这样......在一个测试中,我希望 Foo.someMethod() 返回某个值,而在另一个测试中,我希望它返回一个不同的值.我遇到的问题是,我似乎需要重建模拟才能使其正常工作.我想避免重建模拟,并在每个测试中使用相同的对象.

So, I'm creating a mock object as a static variable on the class level like so... In one test, I want Foo.someMethod() to return a certain value, while in another test, I want it to return a different value. The problem I'm having is that it seems I need to rebuild the mocks to get this to work correctly. I'd like to avoid rebuilding the mocks, and just use the same objects in each test.

class TestClass {

    private static Foo mockFoo;

    @BeforeClass
    public static void setUp() {
        mockFoo = mock(Foo.class);
    }

    @Test
    public void test1() {
        when(mockFoo.someMethod()).thenReturn(0);

        TestObject testObj = new TestObject(mockFoo);

        testObj.bar(); // calls mockFoo.someMethod(), receiving 0 as the value

    }

    @Test
    public void test2() {
        when(mockFoo.someMethod()).thenReturn(1);

        TestObject testObj = new TestObject(mockFoo);

        testObj.bar(); // calls mockFoo.someMethod(), STILL receiving 0 as the value, instead of expected 1.

    }

}

在第二个测试中,当调用 testObj.bar() 时,我仍然收到 0 作为值...解决此问题的最佳方法是什么?请注意,我知道我可以在每个测试中使用不同的 Foo 模拟,但是,我必须从 mockFoo 链接多个请求,这意味着我必须这样做在每个测试中链接.

In the second test, I'm still receiving 0 as the value when testObj.bar() is called... What is the best way to resolve this? Note that I know I could use a different mock of Foo in each test, however, I have to chain multiple requests off of mockFoo, meaning I'd have to do the chaining in each test.

推荐答案

首先不要让 mock 静态化.将其设为私有字段.只需将您的设置类放在 @Before 而不是 @BeforeClass 中.它可能会运行一堆,但它很便宜.

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

其次,你现在拥有它的方式是让一个模拟返回不同的东西的正确方法,具体取决于测试.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

这篇关于如何告诉 Mockito 模拟对象在下次调用时返回不同的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:如何正确匹配 Mockito 中的可变参数 下一条:使用 Mockito 从模拟中抛出已检查的异常

相关文章

最新文章