【问题标题】:mock injected class in Akka actor在 Akka 演员中模拟注入类
【发布时间】:2017-02-06 11:26:38
【问题描述】:

我正在使用 PowerMock,我已经看到使用 @InjectMock 我可以在我的测试中获得注入的类。

但我需要的是使用一个注入了类的 Akka actor,针对该 actor 运行测试并在其中注入一个模拟类。

class A extends Actor{

  @Inject private B b;//How can I mock this class?

}

@Test
public test(){
          final Props props = Props.create(A.class, new A());
        testActorRef = TestActorRef.create(actorSystem, props);
           Future<Object> ask = Patterns.ask(testActorRef);


}

只是为了澄清源代码不能修改。

【问题讨论】:

    标签: java unit-testing mockito akka powermockito


    【解决方案1】:

    最简单的方法是改成构造函数注入:

    class A extends Actor{
      private final B b;//How can I mock this class?
      A(@Inject  B b){
        this.b=b;
      }
    }
    

    这导致了这个测试:

    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); 
    
    @Mock private B mockedB;
    
    @Test
    public test(){
              // configure mockedB here
              A a = new A(mockedB);
    
              // do something with a
              // verify method invocations on b
    }
    

    【讨论】:

    • 我换个问题,恐怕源代码不能修改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多