当spy()为真实对象时,超类字段未分配给任何值

时间:2014-03-03 06:36:50

标签: java unit-testing junit mockito powermock

以下是我的课程

class Parent{
    private AddressService addressService = ServiceLocator.getService(AddressService.class);

    protected void doSomeJob(){
        addressService.doThat();
    }
}

class Child extends Parent{

    protected void doSomeJob(){
        super.doSomeJob();
    }

}

@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceLocator.class})
class ChildTest{

    @Test
    public void doSomeJob(){
        PowerMockito.mockStatic(ServiceLocator.class);
        AddressService addressService = Mockito.mock(AddressService.class);
        PowerMockito.when(ServiceLocator.getService(AddressService.class)).thenReturn(addressService);

        Child original = new Child();
        Child spiedObj = PowerMockito.spy(original);
        spiedObj.doSomeJob();
    }

}

这里ServiceLocator.getService()是一个静态方法,它从应用程序上下文中查找并返回bean。所以,我嘲笑那个静态类,并在它要求AddressService.class时要求返回ServiceLocator.getService(AddressService.class)实例。

我的单元测试时spy()/mock()地址服务实例的子类没有分配任何值。但是当我使用new运算符创建实例时,我可以看到为该字段分配了模拟AddressService。我在这里缺少什么,当我对它的子实例执行spy()时,如何为该父字段赋值?

由于

1 个答案:

答案 0 :(得分:0)

由于我没有看到任何答案,我尝试了以下它并且工作正常(我试图避免这样做)

@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceLocator.class})
class ChildTest{

    @Test
    public void doSomeJob(){
        PowerMockito.mockStatic(ServiceLocator.class);
        AddressService addressService = Mockito.mock(AddressService.class);
        // commented as no more required
        // PowerMockito.when(ServiceLocator.getService(AddressService.class)).thenReturn(addressService);

        Child original = new Child();
        Child spiedObj = PowerMockito.spy(original);
        // using Whitebox API
        Whitebox.setInternalState(spiedObj, AddressService.class, addressService);
        spiedObj.doSomeJob();
    }

}

这里我使用了Whitebox API来设置成员变量。