模拟最终课程变量

时间:2020-04-28 15:02:31

标签: unit-testing junit4 powermockito

我正在尝试测试使用了类的最终实例的类。我没有得到如何创建此最终对象的模拟(在我们的示例foo中)。经过大量挖掘之后,我开始使用powermockito和whenNew方法。我不确定我是不是对JUnits陌生,是否做得正确。 看完之后,我将@PrepareForTest更改为Sample.class(之前是Foo.class),然后foo和koo都为空。

Foo类

public class Foo{
  void hello(){
  }
}

班级样本

public class Sample{
  private final Foo foo= new Foo();
  private Koo koo = new Koo();
  String run(){
    String strr = koo.something();
    return foo.hello();
  }
}

测试类

@RunWith(PowerMockRunner.class)
@PrepareWith({Sample.class})
public class SampleTest{
  @InjectMocks
  private Sample sample;

  @Mock
  private Koo koo;

  @Test
  void run(){
    Foo foo = PowerMockito.mock(Foo.class);
    PowerMockito.whenNew(Foo.class).withNoArguments.thenReturn(foo);

    when(koo.something()).thenReturn("abc");
    when(foo.hello()).thenReturn("def");
    String check = sample.run();
    assertEquals("abc", check);
  }
}

1 个答案:

答案 0 :(得分:0)

foo是一个实例变量,在实例化Sample类时将对其进行初始化。如果要使用 whenNew 模拟此实例变量,则应在执行测试方法之前在加载Sample类时发生这种情况。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Sample.class })
public class SampleTest {

  @InjectMocks
  private Sample sample;

  @BeforeClass 
  public static void setUp() throws Exception {

    Foo foo = PowerMockito.mock(Foo.class);
    Mockito.when(foo.hello()).thenReturn("def");
    PowerMockito.whenNew(Foo.class).withNoArguments().thenReturn(foo);
  }

  @Test
  public void run() throws Exception {

    String check = sample.run();
    Assert.assertEquals("def", check);
  }
}