我可以模拟像printMyValue(String value)这样的方法; 喜欢 when(myClass.printMyValue(anyString())然后返回"某些值&#34 ;;
但我怎么能模拟printMyValue(MyClass值);
答案 0 :(得分:0)
您可以使用“any”方法。你无法静态导入它。您的代码将如下所示:
package jtsandbox;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Explains mocking question from http://stackoverflow.com/questions/29392623/how-to-mock-a-method-which-takes-class-as-parameter/29393040#29393040
* @author Jason W. Thompson (https://plus.google.com/+JasonWThompson_SoftwareDeveloper)
*/
public class TestStuff
{
/**
* Tests mocking
* @throws Exception An exception is not expected to be thrown
*/
@Test
public void testmethod() throws Exception
{
// Given
final Foo mockFoo = mock(Foo.class);
when(mockFoo.printMyValue(Mockito.<Class<?>>any())).thenReturn("Hi!");
// When
final String answer = mockFoo.printMyValue(String.class);
// Then
assertThat(answer, is("Hi!"));
}
public interface Foo
{
public String printMyValue(Class<?> clazz);
}
}
答案 1 :(得分:-1)
您可以使用Mockito的any
匹配器:
when(myClass.printMyValue(any(MyClass.class)).thenReturn("Some value");