2016-10-18 2 views
-1

나는이 다음 시험 방법 :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을 반환하지만 디버깅 할 때 예외가 throw되지 않고 프로그램이 true을 반환하는 것을 볼 수 있습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 당신이 모의 객체가 삽입 된 객체 인스턴스화 안 모든

+1

try 'this = new AccountManagerImpl (null);' – vikingsteve

+0

이미 시도해 보았습니다. 이것은 Mockito가 인터페이스를 초기화 할 수 없기 때문에 수행 할 수 없습니다. @InjectMocks private AccountManagerImpl accountManager 동일한 오류가 발생합니다 – JosepRivaille

+0

질문에 대한 답변은 [이 페이지] (https : // github)에 나와 있습니다. .com/mockito/mockito/wiki/Mocking-Object-Creation) –

답변

4

먼저 대신

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

를, 이것을 사용 :

@InjectMocks 
private AccountManager accountManager; 

을 그럼 당신은 Mockito 러너 사용하는 경우 :

@RunWith(MockitoJUnitRunner.class) 

직접 모의하지 마십시오.

클래스가 조롱 객체를 사용하게

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

:

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

그리고 마지막 지점 : 당신이 당신의 레지스터 방법에서 지역 변수를 가지고 있기 때문에 당신의 조롱에 아무 소용이 없습니다.

관련 문제