2016-02-29 91 views
0

我使用PowerMockito来嘲笑私有方法。但相反被嘲笑它被称为。我需要测试一下调用privateMethod()的strangeMethod()。Mocked私有方法被称为而不是被嘲弄

这里是我的测试类:

public class ExampleService { 
    public String strangeMethod() { 
     privateMethod(); 
     return "Done!"; 
    } 

    private String privateMethod() { 
     throw new UnsupportedOperationException(); 
    } 
} 

我的测试方法:

@Test 
public void strangeMethodTest() throws Exception { 
    ExampleService exampleService = PowerMockito.spy(new ExampleService()); 
    PowerMockito.when(exampleService, "privateMethod").thenReturn(""); 
    exampleService.strangeMethod(); 
} 

由于测试我得到UnsupportedOperationException异常的结果。这意味着,该privateMethod()被调用。

+1

你确定你需要这个摆在首位?这看起来很肮脏,一种方法是私人的原因。 – Neijwiert

+1

尝试使用'@PrepareForTest({ExampleService.class})'和'@RunWith(PowerMockRunner.class)'注释您的测试类' – troig

回答

2

当您使用PowerMockito.spy(new ExampleService());所有方法调用首先将被委派给实际类的实例。你为何要在行得到UnsupportedOperationException

PowerMockito.when(exampleService, "privateMethod").thenReturn("");

如果你想避免调用真正的方法,然后用PowerMockito.mock(ExampleService.class);doCallRealMethod/thenCallRealMethod的方法,它不应该被嘲笑。

这个例子表明,私有方法嘲笑:

类:

public class ExampleService { 
    public String strangeMethod() { 

     return privateMethod(); 
    } 

    private String privateMethod() { 
     return "b"; 
    } 
} 

测试:

@PrepareForTest(ExampleService.class) 
@RunWith(PowerMockRunner.class) 
public class TestPrivate { 

    @Test 
    public void strangeMethodTest() throws Exception { 
     ExampleService exampleService = PowerMockito.spy(new ExampleService()); 
     PowerMockito.when(exampleService, "privateMethod").thenReturn("a"); 
     String actual = exampleService.strangeMethod(); 

     assertEquals("a",actual); 
    } 

} 
+0

我的示例仍然使用'spy'。所以真正的方法仍然被称为一次,当它被嘲笑。正如我上面提到的,你需要使用'PowerMockito.mock'来避免真正的方法调用。 –

+0

但是,如果我嘲笑我的exampleService对象,我该如何测试该方法返回“完成!”? – Sviatlana

+1

对'strangeMethod'使用doCallRealMethod或thenCallRealMethod。例如:'PowerMockito.when(exampleService.strangeMethod())。thenCallRealMethod()'。对不起,我是来自我的手机,所以方法名称可能有点不正确或有错别字。 –