如何使用 Mockito 模拟 System.getProperty

Rag*_*ghu 6 java unit-testing mockito

我在 org.mockito.plugins.MockMaker 文件中添加了 mock-maker-inline 文本并将其放置在 test/resources/mockito-extensions

在我的测试用例中,我使用:

System system = mock(System.class);
when(system.getProperty("flag")).thenReturn("true");`
Run Code Online (Sandbox Code Playgroud)

但我收到以下异常:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Run Code Online (Sandbox Code Playgroud)

感谢任何建议

Jos*_*ino 15

您还可以使用真实的方法,在每次测试之前和之后准备和删除配置:

@Before
public void setUp() {
    System.setProperty("flag", "true");
}

@After
public void tearDown() {
    System.clearProperty("flag");
}
Run Code Online (Sandbox Code Playgroud)


gly*_*ing 6

System.getProperty()方法是static 的,为了模拟它,您需要使用PowerMock

这是一个例子:

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;

import static org.junit.Assert.assertEquals;

@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
public class ATest {

    @Test
    public void canMockSystemProperties() {
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.getProperty("flag")).thenReturn("true");

        assertEquals("true", System.getProperty("flag"));
    }
}
Run Code Online (Sandbox Code Playgroud)

这使用:

  • junit:junit:4.12
  • org.mockito:mocktio-core:2.7.19
  • org.powermock:powermock-api-mockito2:1.7.0
  • org.powermock:powermock-module-junit4:1.7.0

注意:@davidxxx 建议通过将所有System访问隐藏在外观后面来避免模拟这一点,这是非常明智的。避免模​​拟的另一种方法System是在运行测试时将所需的值实际设置为系统属性,系统规则提供了一种在 Junit 测试上下文中设置和拆除系统属性期望的简洁方法。