Mockito 何时/然后不返回预期值 [英] Mockito when/then not returning expected value

查看:22
本文介绍了Mockito 何时/然后不返回预期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用任何"匹配器来存根此 getKeyFromStream 方法.我尝试过更加明确和不明确(anyObject()),但似乎无论我尝试什么,这个存根都不会在我的单元测试中返回 fooKey.

I'm trying to stub this getKeyFromStream method, using the 'any' matchers. I've tried being more explicit and less explicit (anyObject()), but it seems like no matter what I try, this stub will not return the fooKey in my unit test.

我想知道是因为它受到保护还是我遗漏了其他东西或做错了什么.我在整个测试中还有其他 when/then 语句正在运行,但由于某种原因,这里不是.

I'm wondering if it is because it is protected or there is something else I'm missing or doing incorrectly. I have other when/then statements throughout the tests that are working but for some reason here, it is not.

注意:getKeyFromStream 一般使用 byteArrayInputStream,但我正在尝试将其与 InputStream 匹配,我都尝试过均无济于事.

Note: The getKeyFromStream generally uses a byteArrayInputStream, but I'm trying to match it with an InputStream, I've tried both to no avail.

public class FooKeyRetriever() //Mocked this guy
{
    public FooKey getKey(String keyName) throws KeyException {

        return getKeyFromStream(getKeyStream(keyName, false), keyName);
    }

    //Stubbed this method to return a key object which has been mocked
    protected FooKey getKeyFromStream(InputStream keyStream, String keyName){
        //Some code
        return fooKey;
    }
}

单元测试

@Mock
private FooKeyRetriever mockKeyRetriever;

@Mock
private FooKey fooKey;

@Before
public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
}

@Test
public void testGetFooKey() throws Exception {



    when(foo.getKeyFromStream(any(InputStream.class),any(String.class))).thenReturn(fooKey);

    FooKey fooKey = mockKeyRetriever.getKey("irrelevant_key");

    assertNotNull(fooKey);
}

推荐答案

你的单元测试的问题是,你试图模拟你想要测试的实际类的方法,但你实际上不能调用一个模拟方法,因为这将返回 null ,除非您在该调用的方法上声明一个模拟返回值.通常,您只模拟外部依赖项.

The problem with your unit-test is, that you are trying to mock a method of your actual class which you want to test but you can't actually invoke a mock method as this will return null unless you declare a mocked return value on that invoked method. Usually, you only mock external dependencies.

实际上有两种方法可以创建测试对象:mockspy.入门者将根据您提供的类创建一个新对象,该对象具有内部状态 null 并且在每个调用的方法上都返回 null.这就是为什么您需要为方法调用定义某些返回值.spy 另一方面,如果为某些方法定义了模拟定义",则会创建一个真实对象并拦截方法调用.

There are actually two ways to create test-objects: mock and spy. The primer one will create a new object based on the class you provided which has internal state null and also return null on every invoked method. That's why you need to define certain return values for method invocations. spy on the other hand creates a real object and intercepts method invocations if "mock definitions" are defined for certain methods.

Mockito 和 PowerMock 提供了两种定义模拟方法的方法:

Mockito and PowerMock provide two ways of defining your mocked methods:

// method 1
when(mockedObject.methodToMock(any(Param1.class), any(Param2.class),...)
    .thenReturn(answer);
when(mockedObject, method(Dependency.class, "methodToMock", Parameter1.class, Parameter2.class, ...)
    .thenReturn(answer);

// method 2
doReturn(answer).when(mockedObject).methodToMock(param1, param2);

不同之处在于,方法 1 将执行方法实现,而后一个不会.如果您处理 spy 对象,这一点很重要,因为您有时不想在调用的方法中执行真正的代码,而只是替换代码或返回预定义的值!

The difference is, that the method 1 will execute the methods implementation while the later one won't. This is important if you deal with spy objects as you sometimes don't want to execute the real code inside the invoked method but instead just replace the code or return a predefined value!

尽管 Mockito 和 PowerMock 提供了一个 doCallRealMethod(),您可以定义它来代替 doReturn(...)doThrow(...),这将在您的真实对象中调用并执行代码,并忽略任何模拟方法返回语句.但是,在您想要模拟被测类的方法的情况下,这并不是很有用.

Although Mockito and PowerMock provide a doCallRealMethod() which you can define instead of doReturn(...) or doThrow(...), this will invoke and execute the code within your real object and ignores any mocked method return statements. Though, this is not that useful in your case where you want to mock a method of your class under test.

方法实现可以被

doAnswer(Answer<T>() { 
    @Override 
    public T answer(InvocationOnMock invocation) throws Throwable {
        ...
    }
)

您可以简单地声明被调用方法的逻辑应该是什么.您可以利用它来返回受保护方法的模拟结果,因此如下所示:

where you simply can declare what the logic of the invoked method should be. You can utilize this to return the mock result of the protected method therefore like this:

import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;

import java.io.InputStream;

import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class FooKeyRetrieverTest {

    @Test
    public void testGetFooKey() throws Exception {
        // Arrange
        final FooKeyRetriever sut = spy(new FooKeyRetriever());
        FooKey mockedKey = mock(FooKey.class);

        doReturn(mockedKey)
            .when(sut).getKeyFromStream(any(InputStream.class), anyString());
        doAnswer(new Answer<FooKey>() {

            public FooKey answer(InvocationOnMock invocation) throws Throwable {
                return sut.getKeyFromStream(null, "");
            }
        }).when(sut).getKey(anyString());

        // Act
        FooKey ret = sut.getKey("test");

        // Assert
        assertThat(ret, sameInstance(mockedKey));
    }
}

上面的代码可以工作,但是请注意,这与简单地将 getKey(...) 的返回值声明为

The code above works, however note that this has the same semantic as simply declaring a return value for the getKey(...) as

doReturn(mockedKey).when(sut).getKey(anyString());

尝试仅使用以下内容修改 getKeyFromStream(...):

Trying to modify only getKeyFromStream(...) with something like this:

doReturn(mockedKey)
    .when(sut).getKeyFromStream(any(InputStream.class), anyString());

不修改您的被测系统 (SUT) 的 getKey(...) 将无法实现任何实际代码 getKey(...) 将被执行.但是,如果您模拟 sut 对象,则无法调用 //Act 部分中的方法,因为这将返回 null.如果你尝试

without modifying getKey(...) of your System-Under-Test (SUT) won't achieve anything as the real code of getKey(...) would be executed. If you however mock the sut-object, you could not invoke the method in your // Act section as this would return null. If you try

doCallRealMethod().when(sut).getKey(anyString());

在模拟对象上,将调用真正的方法,如前所述,这也将调用 getKeyFromStream(...)getKeyStream(...) 的真正实现 不管你指定什么模拟方法.

on a mock object, the real method woulb be called and as mentiond beforehand, this would also invoke the real implementations of getKeyFromStream(...) and getKeyStream(...) regardless what you specified as mock-method.

正如您自己可能看到的那样,实际测试类的模拟方法并没有那么有用,而且给您带来的负担比它提供的任何好处都多.因此,如果您想要或需要测试私有/受保护的方法,或者您坚持只测试公共 API(我会推荐),这取决于您或您的企业的政策.您还可以重构您的代码 以提高可测试性,尽管主要目的是重构应该是提高整体代码设计.

As you probably can see by yourself, mocking methods of your actual class under test is not that useful and puts more burden to you than it provides any good. Therefore, it's up to you or your enterprise' policy if you want or need to test private/protected methods at all or if you stick to testing only the public API (which I would recommend). You also have the possibility to refactor your code in order to improve testability although the primary intent of refactoring should be to improve the overall design of your code.

这篇关于Mockito 何时/然后不返回预期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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