我有一个在测试中的SomeService的someMethod中调用的AuthenticationManager.authenticate(username,password)方法。AuthenticationManager注入到SomeService中:
@Component
public class SomeService {
    @Inject
    private AuthenticationManager authenticationManager;
    public void someMethod() {
        authenticationManager.authenticate(username, password);
        // do more stuff that I want to test
    }
}现在对于单元测试,我需要authenticate方法来假装它工作正常,在我的例子中什么也不做,这样我就可以测试方法本身是否做了预期的工作(根据单元测试原则在其他地方测试身份验证,但是需要在该方法内部调用authenticate ),所以我想,我需要SomeService使用一个模拟的AuthenticationManager,当authenticate()被someMethod()调用时,它只会返回,不做任何其他事情。
我如何使用PowerMock (或EasyMock / Mockito,它们是PowerMock的一部分)来实现这一点?
发布于 2012-02-14 23:03:57
使用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关键字,这是一种在练习测试驱动开发的同时工作/设计测试和代码的简洁方法。
希望这能有所帮助。
https://stackoverflow.com/questions/9277710
复制相似问题