我具有以下需要测试的类结构。基本上,要测试的类需要从基类,静态的final字段初始化和注入的字段中模拟受保护的方法:
public class BaseItemScan {
protected String initItem(){
...
}
}
public class ItemScan extends BaseItemScan {
@Inject
@Autowired
ItemScanHelper scanHelper;
private static final ItemFactory if = ItemFactory.getInstance();
public void handleItem(){
super.initItem();
...
}
}
工厂类包含一个构造函数和一个getInstance方法:
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;
}
}
}
如何测试handleItem?是否可以使用injectmocks并同时初始化静态字段?由于没有ItemFactory的实例,因此以下代码将失败:
public class ItemScanTest {
@InjectMocks
ItemScan itemScan= new ItemScan();
@Mock
ItemScanHelper scanHelper;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Test
void testHandleItem() {
itemScan.handleItem();
}
}