Mockito:保存模拟参数并从另一个函数返回它 [英] Mockito: save mock argument and return it from another function

查看:39
本文介绍了Mockito:保存模拟参数并从另一个函数返回它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现类似这种结构的东西.

主类:

公共类连接{byte[] read() 抛出异常{//读取一些数据返回数据;}void write(byte[] data) 抛出异常{//写入一些数据}}

测试类:

公共类ConnectionTest{私有静态字节 [] 模拟数据;私人连接连接;公共连接 createMockConnection() {Connection mockConnection = mock(Connection.class);尝试 {doAnswer(新答案(){@覆盖public Object answer(InvocationOnMock invocation) 抛出 Throwable {mockData = (byte[]) invocation.getArguments()[0];返回模拟数据;}}).when(mockConnection).write(any(byte[].class));当(mockConnection.read()).thenReturn(mockData);} catch (Exception e) {}返回模拟连接;}@前public void createConnection() 抛出异常 {连接 = createMockConnection();}@后public void destroyConnection() 抛出异常 {连接 = 空;}@测试public void testCallbackConnection() 抛出异常 {字节 [] 数据 = 新字节 [] {1,2,3,4};连接.写(数据);assertArrayEquals(data, connection.read());}

当我存根 write()read() 方法时,

保存的值 mockData 不包含实际的数据缓冲区.如何获得 testCallbackConnection() 函数中传递的实际值?

谢谢!

更新:

我在 createMockConnection() 函数中模拟 write() 和 read() 方法:

doAnswer(new Answer() {@覆盖public Object answer(InvocationOnMock invocation) 抛出 Throwable {mockData = (byte[]) invocation.getArguments()[0];返回模拟数据;}}).when(mockConnection).write(any(byte[].当(mockConnection.read()).thenReturn(mockData);

我有真正的连接,通过回调写/读函数测试,它工作正常.然后我想编写单元测试,以防我无法访问真正的连接.在这种情况下,我创建 mockConnection 和存根 write()(尝试在 mockData 字段中保存传递的 arg)和 read()(返回之前保存在 write 方法 arg 中的)方法.

我做错了什么?

解决方案

Issues with Connection 尽管有 Connection,但您需要更改第一个 Answer 的使用方式并使用thenAnswer() 代替 thenReturn() 用于您的 read() 方法.基本上,您的测试代码没有看到 mockData 引用的更新.

createMockConnection() 的新代码是:

公共连接 createMockConnection() {Connection mockConnection = mock(Connection.class);尝试 {doAnswer(new Answer() {@覆盖public Void answer(InvocationOnMock invocation) 抛出 Throwable {mockData = (byte[]) invocation.getArguments()[0];返回空;}}).when(mockConnection).write(any(byte[].class));when(mockConnection.read()).thenAnswer(new Answer() {@覆盖public byte[] answer(InvocationOnMock invocation) 抛出 Throwable {返回模拟数据;}});} catch (Exception e) {}返回模拟连接;}

注意对 write() 方法的第一个 Answer 实例的更改.答案的类型表示返回类型.由于 write() 方法不返回任何内容,您的 Answer 实例应该是 Answer 类型,其中您的 answer() 方法返回 null 因为 Void 类型没有实例 - 只有 null 可以转换为它.

其次,read()Answer 实例现在已经存在,代替了之前使用的 thenReturn().>

希望有帮助.如果需要,请向我询问更多问题.

I want to implement something like this construction.

Main class:

public class Connection {

    byte[] read() throws Exception 
    {
      // read some data
      return data;
    }

    void write(byte[] data) throws Exception 
    {
      // write some data
    }
}

Test class:

public class ConnectionTest 
{
    private static byte[] mockData;
    private Connection connection;

    public Connection createMockConnection() {
        Connection mockConnection = mock(Connection.class);

        try {
            doAnswer(new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    mockData = (byte[]) invocation.getArguments()[0];
                    return mockData;
                }
            }).when(mockConnection).write(any(byte[].class));

            when(mockConnection.read()).thenReturn(mockData);
        } catch (Exception e) {}

        return mockConnection;
    }

    @Before
    public void createConnection() throws Exception {
        connection = createMockConnection();
    }

    @After
    public void destroyConnection() throws Exception {
        connection = null;
    }

    @Test
    public void testCallbackConnection() throws Exception {
        byte[] data = new byte[] {1,2,3,4};
        connection.write(data);

        assertArrayEquals(data, connection.read());
   }

Saved value mockData doesn't contains actual data buffer when I stubbing write() and read() methods. How I can get actual value passed in testCallbackConnection() function?

Thank you!

UPDATE:

I mock write() and read() methods in createMockConnection() function:

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        mockData = (byte[]) invocation.getArguments()[0];
        return mockData;
    }
}).when(mockConnection).write(any(byte[].

when(mockConnection.read()).thenReturn(mockData);

I have real connection, that tested by callback write/read functions and it works fine. Then I want write unit test in case I haven't access to real connection. In this case I create mockConnection and stub write() (try save passed arg in mockData field) and read() (return earlier saved in write method arg) methods.

What am I doing wrong?

解决方案

Issues with Connection notwithstanding, you need to change how you are using the first Answer and make use of thenAnswer() in lieu of thenReturn() for your read() method. Basically, your test code isn't seeing the update to the reference of mockData.

The new code for createMockConnection() is:

public Connection createMockConnection() {
    Connection mockConnection = mock(Connection.class);

    try {
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                mockData = (byte[]) invocation.getArguments()[0];
                return null;
            }
        }).when(mockConnection).write(any(byte[].class));

        when(mockConnection.read()).thenAnswer(new Answer<byte[]>() {
            @Override
            public byte[] answer(InvocationOnMock invocation) throws Throwable {
                return mockData;
            }
        });
    } catch (Exception e) {}

    return mockConnection;
}

Note the change to the first Answer instance for the write() method. The type of the answer indicates the return type. Since the write() method doesn't return anything, your Answer instance should be of type Answer<Void> where your answer() method returns null because the Void type has no instances - only null can be cast to it.

Secondly, your Answer instance for the read() now exists, in lieu of the previous use of thenReturn().

I hope that helps. Ping me with further questions if needed.

这篇关于Mockito:保存模拟参数并从另一个函数返回它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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