Mockito什么时候/然后不返回期望值 [英] Mockito when/then not returning expected value

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

问题描述

我试图使用'any'匹配器将这个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);

区别在于,method 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天全站免登陆