简体   繁体   English

在Mockito中存根返回零的函数

[英]Stubbing Out a Null-Returning Function in Mockito

I've been using JUnit and Mockito in an attempt to test how a particular networking module affects its input and output streams. 我一直在使用JUnit和Mockito来测试特定的网络模块如何影响其输入和输出流。 To facilitate testing, I've created a set of mock network object streams (ie an instance of an ObjectInputStream and an instance of an ObjectOutputStream ) and stubbed out the methods I want to be testing in a fashion similar to the following code snippet: 为了方便测试,我创建了一组模拟网络对象流(即ObjectInputStream的实例和ObjectOutputStream的实例),并以类似于以下代码段的方式列出了要测试的方法:

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import static org.mockito.Mockito.*;
import org.junit.Test;  

public class NetworkTester
{
    @Test
    public void ModuleRespondsToServerRequest() throws Exception
    {
        ObjectInputStream mockClientIn = mock(ObjectInputStream.class);
        ObjectOutputStream mockClientOut = mock(ObjectOutputStream.class);

        when(mockClientIn.readObject()).thenReturn("Sent from Server");

        // Initialize module and connect it to the network...

        verify(mockClientOut, timeout(100).atLeastOnce()).writeObject(isNotNull());
    }
}

However, when I try to compile and run this code, I get a null pointer exception at the line "when(mockClientIn.readObject()).thenReturn("Sent from Server");". 但是,当我尝试编译并运行此代码时,在“ when(mockClientIn.readObject())。thenReturn(“从服务器发送”);“行处得到空指针异常。 I believe that this is caused by the fact that the "readObject()" function is returning a null pointer when called on the stubbed object, but I don't know if it's possible to bypass this behavior. 我相信这是由于以下事实引起的:当在存根对象上调用“ readObject()”函数时,它会返回空指针,但是我不知道是否有可能绕过此行为。

Is there any way to stub this function (or similar null returning functions) using Mockito? 有什么方法可以使用Mockito存根该函数(或类似的null返回函数)? Thanks in advance for your help. 在此先感谢您的帮助。

Mockito cannot mock readObject() since it is final. Mockito无法模拟readObject()因为它是最终的。 You could try PowerMockito or consider redesigning your code for easier testability. 您可以尝试使用PowerMockito或考虑重新设计代码以简化可测试性。 See a discussion on the topic here . 此处查看有关该主题的讨论。

If you do a view source you will notice that the method is final. 如果执行视图源,则将注意到该方法是最终的。

public final Object readObject()

Try wrapping the dependency with another object. 尝试用另一个对象包装依赖项。 See: Final method mocking 请参阅: 最终方法模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM