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

How to tell a Mockito mock object to return something different the next time it is called?(如何告诉 Mockito 模拟对象在下次调用时返回不同的东西?)
本文介绍了如何告诉 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 模拟对象在下次调用时返回不同的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)