在私有静态最终字段的对象上使用InjectMock失败

时间:2018-05-18 17:38:23

标签: testing junit mockito powermock powermockito

我正在为遗留代码编写测试用例,由于某些原因我们不想改变。 代码是这样的

 public class ToBeTested{
    private static final String field1=SomeUtil.getProperty("somekey");        
    @AutoWired
    Someservice service;
 }

在我的Junit中,我正在使用与mockito的powermock并做了类似的事情

public class myTestClass{
      @Mock
      SomeService service;
      @InjectMock
      ToBeTested tested;
}

但是,由于未提供最终字段,InjectMocks无法为ToBeTested创建对象

所以我实现了@BeforeClass并模拟了SomeUtil的静态方法。如果我只有一个测试用例,这可行。但是对于多个测试用例,只有一个通过而其他测试用同样的错误

失败
cannot instantiate @injectmocks field named you haven't provided the instance at field declaration

我已经能够通过使用以下内容解决此问题:

public class myTestClass{
          @Mock
          SomeService service;

          ToBeTested tested;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
        mockStatic(SomeUtil.class);
        when(SomeUtil.getProperty(anyString())).thenReturn("test");
        toBeTested=new ToBeTested();    Whitebox.setInternalState(toBeTested,"someService",someService);
    }
    }

然而,我并不喜欢在Junit中使用WhiteBox内部的反射。 有更好的方法吗?

编辑:添加Rann在评论中建议的代码片段

@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeUtil.class)
public class myTestClass{
      @Mock
      SomeService service;
      @InjectMock
      ToBeTested tested;

    @BeforeClass
    public static void doBeforeClass(){
        mockStatic(SomeUtil.class);
        when(SomeUtil.getProperty(anyString())).thenReturn("test");
    }

    @Test
    public void test1(){
        tested.doSomethingFor1();
    }

    @Test
    public void test2(){
        tested.doSomethingFor2();
    }
}

test1通过罚款。对于test2我得到一个例外

Caused by: org.mockito.exceptions.base.MockitoException: 
Cannot instantiate @InjectMocks field named 'tested' of type 'class com.xyz.ToBeTested'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null

    at org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:72)
    at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:64)
    at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
    ... 23 more
Caused by: java.lang.NullPointerException
    at com.xyz.SomeUtil.getProperty(SomeUtil.java:42)

0 个答案:

没有答案