2016-10-18 10 views
-1

I持って、次の試験方法:Mockitoモックは動作しません正しく

@Override 
    public Boolean register(String email, String name, String password, String password2) { 
     if (password.equals(password2)) { 
      try { 
       String pwd = hashPassword(password); 
       User user = new User(email, name, pwd); 
       AuthStorage authStorage = new AuthStorageImpl(); 
       authStorage.registerNewUser(user); 
       return true; 
      } catch (NoSuchAlgorithmException | AuthStorageException e) { 
       return false; 
      } 
     } 
     // If passwords don't match 
     return false; 
    } 

たぶん、それは例外をThowさんとすべきregisterNewUserを呼び出す:次のクラスメソッドをテストし

@RunWith(MockitoJUnitRunner.class) 
public class AccountManagerTest { 

    @InjectMocks 
    private AccountManager accountManager = new AccountManagerImpl(null); 

    @Mock 
    private AuthStorage authStorage; 

    @Before 
    public void setup() { 
     MockitoAnnotations.initMocks(this); 
    } 

    /* REGISTER TESTS */ 

    @Test 
    public void test_whenRegister_withAlreadyExistingEmail_thenDoNotRegister() throws AuthStorageException { 
     String email = "[email protected]"; 
     String name = "Foo"; 
     String password = "123456"; 
     String password2 = "123456"; 

     doThrow(new AuthStorageException("Email already in use")).when(authStorage).registerNewUser(Matchers.any()); 
     assertFalse(accountManager.register(email, name, password, password2)); 
    } 
} 

このメソッドはfalseを返しますが、デバッグ時には例外がスローされず、プログラムはtrueを返します。私は間違って何をしていますか?

+1

私はすでにそれを試してみました。これは新しいAccountManagerImpl(null); ' – vikingsteve

+0

です。これはできません。なぜなら、Mockitoはインターフェースをインスタンス化できないからです。 @ InjectMocks private AccountManagerImpl accountManager 私は同じエラーが発生します – JosepRivaille

+0

あなたの質問に対する答えは[このページにあります](https:// github .com/mockito/mockito/wiki/Mocking-Object-Creation) –

答えて

4

あなたはモックが挿入されたオブジェクトインスタンス化してはならないまず第一に:あなたはMockitoランナーを使用する場合は、

@InjectMocks 
private AccountManager accountManager; 

:これを使用する代わりに、

@InjectMocks 
private AccountManager accountManager = new AccountManagerImpl(null); 

@RunWith(MockitoJUnitRunner.class) 

モックを直接注射しないでください:

@Before 
public void setup() { 
    MockitoAnnotations.initMocks(this); //remove this line 
} 

そして最後のポイント:

AuthStorage authStorage = new AuthStorageImpl(); 
authStorage.registerNewUser(user); 

クラスは、あなたの嘲笑オブジェクトを使用します:あなたはレジスタ方法でローカル変数を持っているので、あなたのモックにも意味がありません。

関連する問題