代码之家  ›  专栏  ›  技术社区  ›  Sunny

对静态方法使用powermockito时出现异常

  •  2
  • Sunny  · 技术社区  · 6 年前

    我想用powermokito模拟静态方法,

    public class DepedencyService {
    
        public static int getImportantValue() {
            return -4;
        }
    }
    
    public class Component {
    
        public int componentMethod() {
            return DepedencyService.getImportantValue();
        }
    }
    

    但它给了我一个例外。

    import static org.testng.Assert.assertEquals;
    import org.easymock.EasyMock;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(DepedencyService.class)
    public class ComponentTest {
        @Test
        public void testComponentMethod() {
            Component c = new Component();
            PowerMockito.mockStatic(DepedencyService.class);
            EasyMock.expect(DepedencyService.getImportantValue()).andReturn(1);
            assertEquals(1, c.componentMethod());
        }
    }
    

    例外情况:

    java.lang.illegalStateException:没有对模拟的最后调用,位于 Oracy.EasyMoC.EasyMoCK.GeTimeForkLaStLead(EasyMoCK.java:520)AT Easy.EasyMoC.EasyMoC.Exk(EasyMoCK.java:498)

    有人能帮我吗?为什么失败了?我刚接触到PowerMockito,不知道在这里做什么!

    2 回复  |  直到 6 年前
        1
  •  0
  •   Nkosi    6 年前

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(DepedencyService.class)
    public class ComponentTest {
        @Test
        public void testComponentMethod() {
            //Arrange        
            int expected = 1;
            PowerMockito.mockStatic(DepedencyService.class);
            Mockito.when(DepedencyService.getImportantValue()).thenReturn(expected);
            Component subject = new Component();
    
            //Act
            int actual = subject.componentMethod();
    
            //Assert
            assertEquals(expected, actual);
        }
    }
    

        2
  •  2
  •   Timothy Truckle Vincent Boutot    6 年前

    STUPID code

    static

    main()