0

테스트 할 SomeService의 someMethod에서 호출되는 AuthenticationManager.authenticate(username,password) 메서드가 있습니다. 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은 을 사용해야합니다. authenticate()someMethod()에 의해 호출 될 때 아무 것도 반환하지 않습니다.

PowerMock (또는 PowerMock의 EasyMock/Mockito)으로 어떻게 할 수 있습니까?

답변

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

+0

쿨, 도움이 된 것을 기쁘게 생각합니다. :) – Brice

관련 문제