将 PowerMockito 与静态方法一起使用时出现异常

Exception while using PowerMockito with static method

我想使用 PowerMockito 模拟静态方法,

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: no last call on a mock available at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520) at org.easymock.EasyMock.expect(EasyMock.java:498)

谁能帮帮我?为什么会失败?我是 PowerMockito 的新手,不知道该做什么!

您似乎在混合模拟框架。

在进行测试之前,您需要妥善安排静态依赖关系

由于 PowerMockito 用于模拟静态 class 那么您应该使用 Mockito 来安排预期的行为

例如

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

也就是说,我建议不要让您的代码与静态依赖项紧密耦合。这使得测试代码变得困难。

您的主要问题是您正在编写 STUPID code(就像我们大多数人一开始所做的那样)您宁愿编写 SOLID 代码。

使用 Powermock 只是对这种糟糕设计的投降。

是的,类 只有 static 个方法被调用 实用程序 类

但是您应该克服这种误解,即 类 提供通用行为应该(只)有 static 方法。

根据经验,整个程序中应该只有一个 non private static 方法,这就是 main().