Mockito:如何使用(instance.meth).thenAnswer没有模拟

时间:2014-11-11 05:06:25

标签: java junit mocking mockito

我试过以下代码:

package ro.ex;

/**
 * Created by roroco on 11/11/14.
 */

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

import static org.mockito.Mockito.*;


public class ExTest extends junit.framework.TestCase {
    class C {
        public String m() {
            return null;
        }
    }

    public void testM() throws Exception {
        when(new C().m()).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                return (String) args[0];
            }
        });

    }
}

我希望我能改变一个真实的实例,而不是模拟,但代码提高:

when() requires an argument which has to be 'a method call on a mock'.

我的问题是:如何修复它。

2 个答案:

答案 0 :(得分:1)

我认为这是您在此处提出问题所创建的示例代码,但实际上,C应该是受测试的类(不是测试中的类)。

Class MyClassToTest {

public String m() {...}

}

现在,在您的测试中,模拟类C. @Mock C c,然后是when(c.m()).thenAnswer....。在测试方法中。

答案 1 :(得分:0)

不确定为什么会这样,但您可以使用spy

public void testM() throws Exception {
    C c = Mockito.spy(new C());

    // actual method
    c.m();

    // stubbed method
    when(c.m()).thenAnswer(...);
}

或者,您可以mock该对象,并在需要时致电thenCallRealMethod()

相关问题