Mockito vs @Configurable

时间:2014-07-13 00:32:43

标签: java spring junit mockito powermock

我试图为一些通常用Spring管理的代码编写JUnit测试。

我们说我有这个:

@Configurable
public class A {
  @Autowired MyService service;

  public void callA() { service.doServiceThings(); }
}

我可以使用Mockito和PowerMock为这个类写一个测试:

@RunWith(PowerMockRunner.class)
public class ATest {
  @Spy MyService service = new MyService();

  @Before void initMocks() { MockitoAnnotations.initMocks(this); }

  @Test void test() {
    @InjectMocks A a = new A(); // injects service into A
    a.callA();
    //assert things
  }
}

但是现在我遇到一个案例,当其他一些类构造A:

的实例时
public class B {
  public void doSomething() {
    A a = new A(); // service is injected by Spring
    a.callA();
  }
}

如何将服务注入到B方法中创建的A实例中?

@RunWith(PowerMockRunner.class)
public class BTest {
  @Spy MyService service = new MyService();

  @Before void initMocks() { MockitoAnnotations.initMocks(this); }

  @Test testDoSomething() {
     B b = new B();
     // is there a way to cause service to be injected when the method calls new A()?
     b.doSomething(); 
     // assert things
  }
}

1 个答案:

答案 0 :(得分:0)

现场注入确实很糟糕,但仍有一件事你可以轻易地实现一个实例化(或者我误解了)。使B通过构造函数注入一个AFactory。

public class B {
    private final AFactory aFactory;
    public B(AFactory aFactory) {
        this.aFactory=aFactory;
    }
    public void doSomething() {
    A a = aFactory.getA();
    a.callA();
    }
}

然后你可以创建一个模拟工厂并通过构造函数将它注入B。