1

I have the following classes, where the second class is a static final field of the first one:

public class BaseItemScan  {


    protected String initItem(){
       ...
    }

}

public class ItemScan extends BaseItemScan {

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

}

The factory class contains a constructor and a getInstance method:

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;
        }
    }
}

How can the handleItem be tested? For the following code:

public class ItemScanTest {

    @InjectMocks
    ItemScan itemScan= new ItemScan();

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

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

}

The error message is:

Caused by: java.lang.IllegalStateException: ItemFactory not initialized!
    at ItemFactory.getInstance(ItemFactory.java:)
    at ItemScan.<clinit>(ItemScan.java:)

1 Answers1

0

Here's the example to do that. I just added the sayHello method to the ItemFactory class to verify the number of invocations. The default constructor was added just because PowerMock was complaining about not having a zero-argument constructor.

@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();
    }
}
Mansur
  • 1,661
  • 3
  • 17
  • 41
  • The example works, but if I try to mock a protected method of the base class, example added, I'm getting a null pointer exception for PowerMockito.when(itemScan, "initItem").thenReturn("0190198785374"); – topProgrammer Jan 25 '20 at 20:09
  • I think that's not relevant to the current question, but you can try this one: https://stackoverflow.com/a/34692471/9985287 – Mansur Jan 25 '20 at 20:20