2015-04-01 99 views
0

我可以模擬像printMyValue(String value)這樣的方法; 像 時(myClass.printMyValue(anyString()),然後返回 「一些價值」;如何模擬以Class爲參數的方法

但我怎麼能嘲笑printMyValue(MyClass的值);

+0

嘗試回答後在這裏編輯:http://stackoverflow.com/questions/5462096/stubbing-a-method-that-takes-classt-as-parameter-with-mockito – KSev 2015-10-21 18:47:34

回答

0

您可以使用 「任何」 的方法你只要不能靜態地導入您的代碼將是這個樣子:

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

可以使用的Mockito的any匹配:

when(myClass.printMyValue(any(MyClass.class)).thenReturn("Some value"); 
相關問題