【问题标题】:How to mock a method which takes Class as parameter如何模拟以类为参数的方法
【发布时间】:2015-04-01 13:52:01
【问题描述】:

我可以模拟 printMyValue(String value); 这样的方法 喜欢 when(myClass.printMyValue(anyString())then return "Some value";

但是我如何模拟 printMyValue(MyClass value);

【问题讨论】:

标签: junit


【解决方案1】:

您可以使用“任何”方法。您只是不能静态导入它。您的代码将如下所示:

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);
    }
}

【讨论】:

    【解决方案2】:

    你可以使用 Mockito 的 any 匹配器:

    when(myClass.printMyValue(any(MyClass.class)).thenReturn("Some value");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多