@Produces方法中@Mock的Junit 4范围

Junit 4 scope of @Mock in @Produces methods

如果使用注解 @Mock

进行模拟,为什么模拟对象在测试后 class 出现 class 并在 @Produced 方法中出现 null
public class MyTest {

   @Rule
   public MockitoRule rule = MockitoJUnit.rule();

   @Rule
   public WeldInitiator weld = WeldInitiator.from(MyTest.class).build();

   //@Mock <-- this wont work. Will be null in the @Produces methods
   private ClassThatSutInjects sutInject= mock(ClassThatSutInjects.class);

   private NeedsTest sut;

   @Before
   public void setup() {
      sut = weld.select(NeedsTest.class).get();
   }

   @Test
   public void doesThisWork() {
      //Arrange
      //Mockito.when(sutInject.multiply(anyInt()))
      // .thenReturn(3);//this has no effect on the mock returned by @Produces

      //Act
      sut.doThis(1234);

      //Assert

  }

  @Produces
  public ClassThatSutInjects mockThatClass() {
      Mockito.when(sutInject.multiply(anyInt())).thenReturn(100);   //<-- this works
      return sutInject;
  }

}

public class NeedsTest {
   @Inject
   ClassThatSutInjects someClass

   public void doThis(int number) {
      return someClass.multiply(number);
   }

}

有两件事让我很困惑,我希望得到一些帮助来理解:

1) @Mock(带注释的字段)在@Producer 方法中为空,但如果我使用 = Mockito.mock(xxx.class) 则初始化。据我所知,这与执行符号的时间与应用 @Rule 的时间有关。更多细节将不胜感激...

2) 我非常希望能够让模拟在不同的测试用例中做不同的事情,但这似乎是不可能的,因为 @Produces 方法是 "stuck in the past" 当 mockito.when( ) 尚未应用。我如何 "arrange" pr。测试用例?有一个测试-class pr。随着时间的推移,测试用例将变得无法维护。代码混乱。

编辑:我发现让我的模拟对象静态化,可以设置我的模拟对象 pr。测试方法。我进行了调试 运行 并注意到生产者返回的对象与 jUnit @Test 中使用的实例不同 - 显然 @Produces 在 MyTest class 的另一个实例上是 运行 ...对我来说仍然没有真正的意义,所以仍然:如果有人有一些知识,请分享它。

正如您已经观察到的,生产者 运行 在对象的不同实例上。

Source(第 8.1 章生产者方法的作用域):

A producer method does not inherit the scope of the bean that declares the method. There are two different beans here: the producer method, and the bean which declares it. The scope of the producer method determines how often the method will be called, and the lifecycle of the objects returned by the method. The scope of the bean that declares the producer method determines the lifecycle of the object upon which the producer method is invoked.

将字段设置为静态可以解决这个问题,但这并不是一个很好的解决方案。