【问题标题】:Mockito vs @ConfigurableMockito vs @Configurable
【发布时间】:2014-07-13 00:32:43
【问题描述】:

我正在尝试为一些通常由 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
  }
}

【问题讨论】:

  • 不容易,这是反对字段注入的绝佳论据。您可能需要使用 Spring 测试上下文。

标签: java spring junit mockito powermock


【解决方案1】:

字段注入很糟糕,但是您仍然可以做一件事来轻松地存根该 A 实例化(或者我可能误解了某事)。让 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();
    }
}

然后你可以创建一个 aFactory 的 Mock 并通过构造函数将其注入 B。

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 2014-08-14
    • 2015-04-02
    • 1970-01-01
    • 2013-02-18
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多