我的模拟模拟怎么能用改变的参数调用原始方法?

时间:2014-09-30 13:27:11

标签: java unit-testing mockito

我正在使用模拟嘲笑。

我想控制方法foo(String a, Date b)

的调用

使用foo(a, fixed_date)

调用原始方法

如何使用mockito API执行此操作?

MyObject myObject = mock(MyObject.class);

        when(myObject.foo(anyString, any(Date.class))
                .thenCallRealMethod();

为什么这不起作用?

它永远不会重定向呼叫

ImagesSorter imagesSorter = spy(new ImagesSorter());
        doReturn(imagesSorter.sortImages(images, user, fakeNowDate)).when(imagesSorter).sortImages(images,user);

1 个答案:

答案 0 :(得分:1)

我有一个解决方案,但它有点hacky,让我们假设foo的返回类型为String

import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;

...

final Date fixedDate = ...;

MyClass myObject = mock(MyClass.class);

when(myObject.foo(anyString(), any(Date.class))).thenAnswer(new Answer<String>() {
        public String answer(InvocationOnMock invocation) throws Throwable {
            // Switch the 2nd argument
            invocation.getArguments()[1] = fixedDate;
            // Then call the real method
            return (String) invocation.callRealMethod();
        }
    }); 

MyClass为例:

public class MyClass {

    public String foo(String s, Date d) {
        return s + d;
    }
}

修改

在您使用ImageSorter的最后一个示例中,我认为您不需要Mockito,一个简单的装饰工具就可以解决问题:

public interface ImageSorter {
    void sortImages(Images images, User user);

    void sortImages(Images images, User user, Date date);
}

public class ImageSorterDecorator implements ImageSorter {

    final ImageSorter delegate;
    final Date fixedDate;

    public ImageSorterDecorator (ImageSorter delegate, Date fixedDate){
        this.delegate = delegate;
        this.fixedDate = fixedDate;
    }

    public void sortImages(Images images, User user){
        delegate.sortImages(images, user, fixedDate);
    }

    public void sortImages(Images images, User user, Date date){
        delegate.sortImages(images, user, fixedDate);
    }
}