0

我有一個AuthenticationManager.authenticate(username,password)方法,它在SomeService的someMethod中被調用。該AuthenticationManager會被注入到SomeService:如何使用PowerMock/Mockito/EasyMock爲依賴注入使用模擬對象?

@Component 
public class SomeService { 
    @Inject 
    private AuthenticationManager authenticationManager; 

    public void someMethod() { 
     authenticationManager.authenticate(username, password); 
     // do more stuff that I want to test 
    } 
} 

現在的單元測試,我需要在認證方法,只是假裝它工作正常,在我的情況什麼都不做,因此,如果該方法本身並沒有預期的工作,我可以測試(根據單元測試原則在別處測試身份驗證,但是需要在該方法內調用身份驗證)所以我想,我需要SomeService來使用嘲諷的AuthenticationManager,它只會返回並在authenticate()someMethod()調用時什麼也不做。

如何使用PowerMock(或EasyMock/Mockito,它是PowerMock的一部分)來做到這一點?

回答

3

隨着你的Mockito可能只是做到這一點與這段代碼(使用JUnit):

@RunWith(MockitoJUnitRunner.class) 
class SomeServiceTest { 

    @Mock AuthenitcationManager authenticationManager; 
    @InjectMocks SomeService testedService; 

    @Test public void the_expected_behavior() { 
     // given 
     // nothing, mock is already injected and won't do anything anyway 
     // or maybe set the username 

     // when 
     testService.someMethod 

     // then 
     verify(authenticationManager).authenticate(eq("user"), anyString()) 
    } 
} 

瞧。如果您想要具有特定行爲,只需使用存根語法;請參閱文檔there。 另請注意,我使用了BDD關鍵字,這是一種在練習測試驅動開發時工作/設計測試和代碼的簡潔方式。

希望有所幫助。

+0

謝謝!真的幫助我徹底改變了我的測試! – Pete 2012-02-15 08:39:24

+0

很酷,我很高興它幫助:) – Brice 2012-02-15 09:02:55