如何模拟静态最终课程

时间:2020-01-25 17:28:46

标签: unit-testing junit static powermock

我有以下类别,其中第二个类别是第一个类别的静态final字段:

out

工厂类包含一个构造函数和一个getInstance方法:

public class BaseItemScan  {


    protected String initItem(){
       ...
    }

}

public class ItemScan extends BaseItemScan {

    private static final ItemFactory if = ItemFactory.getInstance();
    public void handleItem(){
       super.initItem();
       ...
    }

}

如何测试handleItem?对于以下代码:

public class ItemFactory {
    private static ItemFactory INSTANCE = null;

    public static ItemFactory getInstance() {
        if (INSTANCE == null) {
            throw new IllegalStateException("ItemFactory not initialized!");
        } else {
            return INSTANCE;
        }
    }

    public ItemFactory () {
        if (INSTANCE != null) {
            throw new IllegalStateException("ItemFactory already initialized!");
        } else {
            INSTANCE = this;
        }
    }
}

错误消息是:

public class ItemScanTest {

    @InjectMocks
    ItemScan itemScan= new ItemScan();

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

    @Test
    void testHandleItem() {
        itemScan.handleItem();
    }

}

1 个答案:

答案 0 :(得分:0)

这里是执行此操作的示例。我只是将sayHello方法添加到ItemFactory类中以验证调用次数。添加默认构造函数只是因为PowerMock抱怨没有零参数的构造函数。

@RunWith(PowerMockRunner.class)
@PrepareForTest(ItemFactory.class)
class ItemScanTest {

    public ItemScanTest() {}

    private ItemScan itemScan;

    @Mock
    private ItemFactory itemFactory;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(ItemFactory.class);
        Mockito.when(ItemFactory.getInstance()).thenReturn(itemFactory);
        itemScan = new ItemScan();
    }

    @Test
    public void handleItemTest() {
        Mockito.when(itemFactory.sayHello()).thenReturn("HelloHello");
        itemScan.handleItem();
        Mockito.verify(itemFactory, times(1)).sayHello();
    }
}