java - 如何使用 Mockito 模拟 System.getProperty

标签 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");`

但是我得到以下异常:

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.

感谢任何建议

最佳答案

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

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

@After
public void tearDown() {
    System.clearProperty("flag");
}

关于java - 如何使用 Mockito 模拟 System.getProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529605/

相关文章:

java - Mockito 参数捕获器和 only()

scala - 使用 Mockito 对 LazyLogging 进行单元测试

Eclipse 中的 Java Socket 聊天

通过带有凭据的代理进行 Java 请求

java - 如何在一个pom文件中生成两个xmlbeans

java - 如何在对子类进行单元测试时在抽象类中注入(inject)变量?

java - 单元测试从另一个类调用的方法

java - 在 java swing 中创建 X window(X11) 并获取它的 id

Python read_text() 添加额外的字符串

c# - 无法使用 Moq 框架验证在 Select() 内部调用的方法