2014-11-23 122 views
2

我正在學習Spring Core認證,我對單元測試stubs的工作原理有一些疑問。使用存根的Spring JUnit測試究竟如何?

例如我有以下幻燈片:

enter image description here

所以,我認爲,這意味着,在生產環境我有一個AuthenticatorImpl類使用JpaAccountRepo服務\庫這是一個依賴關係它是 本身與一些依賴關係和生產環境(Spring,配置和數據庫)有關。

所以,如果我想測試AuthenticatorImpl單元我不得不刪除鏈接到所有依賴

所以使用stub的方式我必須創建一個存根,我想測試的單位先前的第一個依賴項。在這種情況下,它是JpaAccountRepo這樣我就可以創建一個通用的AccountRepoStub這是一個假的實現不使用一個數據庫,不使用特定的TECNOLOGY訪問數據(我沒有測試JpaAccountRepo所以我可以使用假實現,因爲它是單元測試而不是集成測試)。

它是我的推理權,直到現在呢?

因此,舉例來說,如果這是我的AuthenticatorImpl

public class AuthenticatorImpl implements Authenticator { 
    private AccountRepository accountRepository; 

    public AuthenticatorImpl(AccountRepository accountRepository) { 
     this.accountRepository = accountRepository; 
    } 

    public boolean authenticate(String username, String password) { 
     Account account = accountRepository.getAccount(username); 
     return account.getPassword().equals(password); 
    } 
} 

正如你所看到的構造AuthenticatorImpl()構造採取AccountRepository對象paramether(即一個接口,而不是一個實現)。

所以我可以創建存根命名StubAccountRepository實現AccountRepository接口

class StubAccountRepository implements AccountRepository { 
    public Account getAccount(String user) { 
     return 「lisa」.equals(user) ? new Account(「lisa」, 「secret」) : null; 
    } 
} 

所以finnally我可以創建單元測試實現一個AuthenticatorImplTests類類

import org.junit.Before; import org.junit.Test; ... 

public class AuthenticatorImplTests { 
    private AuthenticatorImpl authenticator; 

    @Before 
    public void setUp() { 
     authenticator = new AuthenticatorImpl(new StubAccountRepository()); 
    } 

    @Test 
    public void successfulAuthentication() { 
     assertTrue(authenticator.authenticate(「lisa」, 「secret」)); 
    } 

    @Test 
    public void invalidPassword() { 
     assertFalse(authenticator.authenticate(「lisa」, 「invalid」)); 
    } 
} 

所以在我的setUp方法我建立一個AuthenticatorImpl對象將其傳遞給我的存根StubAccountRepository所以我刪除具有依賴關係的鏈接,我只測試了AuthenticatorImpl單元。

這是對的還是我錯過了什麼?

Tnx

回答

3

你明白了。

大多數情況下,你並沒有明確地創建一個存根類,但是使用一個模擬框架,如Mockito,它動態地爲你創建它。例如:

AccountRepository stub = mock(AccountRepository.class); 
authenticator = new AuthenticatorImpl(stub); 

when(stub.getAccount("lisa")).thenReturn(new Account(「lisa」, 「secret」));