PowerMocking static does not return expected object

前端 未结 3 1492
长发绾君心
长发绾君心 2021-01-19 22:10

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.

Right now my code looks like this:

3条回答
  •  攒了一身酷
    2021-01-19 22:22

    It seems that you need to add the target test class in the PrepareForTest tag:
    @PrepareForTest({ Calendar.class, Surveillance.class })

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ Calendar.class, Surveillance.class })
    public class SurveillanceDatabaseTest {
        @Test
        public void testFailingDatabase() throws Exception {
            mockStatic(Calendar.class);
            Calendar calendar = new GregorianCalendar();
            calendar.add(Calendar.HOUR, 1);
            when(Calendar.getInstance()).thenReturn(calendar);
            final Surveillance surveillance = new Surveillance();
            surveillance.checkDatabase();
       }
    }
    

    Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.

提交回复
热议问题