【问题标题】:How do I use PowerMock / Mockito / EasyMock to use a mocked object for dependency injection?如何使用 PowerMock / Mockito / EasyMock 使用模拟对象进行依赖注入?
【发布时间】:2012-02-14 13:29:08
【问题描述】:

我有一个AuthenticationManager.authenticate(username,password) 方法,它在被测 SomeService 的 someMethod 中被调用。 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 方法来假装它工作正常,在我的情况下什么都不做,所以我可以测试方法本身是否完成了预期的工作(根据单元测试原则在其他地方测试了身份验证,但是需要在该方法中调用身份验证)所以我在想,我需要SomeService 使用模拟的AuthenticationManager,当authenticate() 被someMethod() 调用时,它只会返回并且什么都不做。

如何使用 PowerMock(或 EasyMock / Mockito,它们是 PowerMock 的一部分)做到这一点?

【问题讨论】:

    标签: unit-testing dependency-injection mockito easymock powermock


    【解决方案1】:

    使用 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 关键字,这是在练习测试驱动开发时工作/设计测试和代码的一种简洁方式。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      相关资源
      最近更新 更多