2013-06-12 65 views
0

在,我與PowerMock測試類我有一個類PowerMocking一個新的實例

EmailMessage msg = new EmailMessage(getExchangeSession()); 

EmailMessage以下實例是一個第三方工具,我嘲笑而getExchangeSession()是enherited保護的方法。我需要嘲笑EmailMessage,但我真的不在意撥打getExchangeSession()的電話。

目前我有以下,但getExchangeSession()方法仍稱:

@RunWith(PowerMockRunner.class) 
@PrepareForTest({EmailProvider.class, ExchangeService.class}) 
public class MyTest { 

    @Test 
    public void test() { 
     EmailMessage emailMessage = createMock(EmailMessage.class); 
     ExchangeService exchangeService = createMock(ExchangeService.class); 
     expectNew(EmailMessage.class, exchangeService).andReturn(emailMessage); 

     // test setup and call to the class under test 
     Email email = new Email(); 
     new EmailProvider().send(email); 
    } 
} 

public class EmailProvider() extends ClassWithProtectedAccess { 
    public void send(Email email) { 
     EmailMessage msg = new EmailMessage(getExchangeSession()); 

     // and here follows the code that I am actually testing 
     // and which works on the msg (EmailMessage) 
     // ... 
    } 
} 

EmailProvider.send的第一行()是它運行getExchangeSession()和再失敗。

所以顯然我不能跳過對getExchangeSession()的電話,我應該也可以嘲笑這種方法。它是否正確? 如果是這樣,在EasyMock中使用PowerMock,我該如何嘲笑這種受保護的方法?

+1

你是否將這些添加到了測試中? @RunWith(PowerMockRunner.class) @PrepareForTest(Test.class)。你也可以查看這個鏈接使用powermock.expectprivate,它可能也適用於受保護的方法(我使用justmock自己所以不是100%確定)編輯(添加鏈接):http://stackoverflow.com/questions/17027582/powermock -easymock-private-void-method-without-invokation – Josh

回答

1

測試其他語句如果你想測試的類有這一行是:

EmailMessage msg = new EmailMessage(getExchangeSession()); 

然後你不能跳過對getExchangeSession()的調用,powermocking的構造函數是EmailMessage--它在構造函數被調用之前被調用,然後返回值被傳遞給EmailMessage(不管它是真實的還是模擬的)。

因此,如果您無法將您的班級設置爲致電getExchangeSession工作,您將需要按照此問題所描述的模擬該呼叫:mocking protected method

0

正如我正確理解您的問題,您期望模擬EmailMessage類,但需要跳過創建實例時的構造函數調用。

... test setup and call to the class under test ... 
    Email email = new Email(); 
    new EmailProvider().send(email); 

問題是你測試的方式。您的意圖是在發送方法中測試代碼。你不能只調用send()方法來測試。您需要通過嘲笑的依賴類來寫代碼測試中發送的聲明()方法,並在類

public void testSend() throws Exception 
{ 
    // you need to suppress the constructor before you mock the class. 
    PowerMockito.suppress(PowerMockito.constructor(EmailMessage.class)); 
    EmailMessage emailMessage = PowerMockito.mock(EmailMessage.class); 
    Email email = new Email(); 
    emailMessage.setSubject(email.getSubject()); 
    // ...your other code here ... 

} 
+0

謝謝你的回答。不幸的是,它並沒有改變任何東西 - getExchangeSession()仍然被調用。 – homaxto

+0

我編輯了答案。請讓我知道您的意見或您的看法,如果您認爲不同 – Libin

+0

我不想在我的代碼中調用EmailMessage.setSubjet(),因爲我需要測試的方法是EmailProvider.send() - 它在處理期間調用EmailMessage.setSubjet()。 – homaxto

相關問題