如何从Java 8和系统类模拟功能接口

发布于 2025-01-27 15:26:25 字数 505 浏览 5 评论 0原文

我想在下面进行模拟:

((Function<String, String>) System::getenv).apply(TransformerConstants.TRANSFORMER_POOL_SIZE)

我尝试使用以下代码:

PowerMockito.when(((Function<String, String>) System::getenv).apply(TransformerConstants.PRECISE_ID_TRANSFORMER_POOL_SIZE)).thenReturn("dsad");

但下面给出的错误:

org.mockito.exceptions.misusing.missingmethodinvocation exception: 当()需要一个必须是“模拟方法的方法”的参数。 例如: 当(mock.getarticles())

I want to mock below call :

((Function<String, String>) System::getenv).apply(TransformerConstants.TRANSFORMER_POOL_SIZE)

I tried using below code :

PowerMockito.when(((Function<String, String>) System::getenv).apply(TransformerConstants.PRECISE_ID_TRANSFORMER_POOL_SIZE)).thenReturn("dsad");

But its giving below error :

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

Let me know how this entire call can be mocked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风柔一江水 2025-02-03 15:26:25

不要尝试模拟 系统:: getenv。相反,构建代码,以便您可以用其他值(模拟或仅在线测试lambda)替换该方法参考:

objectToTest.setGetEnvFunction(key -> testValue);

Don't try to mock System::getenv. Instead, structure your code so that you can replace that method reference with some other value (a mock or just an inline test lambda):

objectToTest.setGetEnvFunction(key -> testValue);
烙印 2025-02-03 15:26:25

我可以这样做:

 @Test
 @SetEnvironmentVariable(key = TransformerConstants.TRANSFORMER_POOL_SIZE, value = "sadsa")
 public void testCreateMapper_invalidTransformerPoolSize(){
     Assert.assertTrue(factory.createMapper(null) instanceof StandardMapper);
 }

I was able to do so this with :

 @Test
 @SetEnvironmentVariable(key = TransformerConstants.TRANSFORMER_POOL_SIZE, value = "sadsa")
 public void testCreateMapper_invalidTransformerPoolSize(){
     Assert.assertTrue(factory.createMapper(null) instanceof StandardMapper);
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文