gpt4 book ai didi

PowerMockito+Junit - 模拟 System.getenv

转载 作者:行者123 更新时间:2023-12-02 06:48:16 27 4
gpt4 key购买 nike

我试图在类里面 mock 的路线是:

String x[] = System.getenv("values").split(",")
for(int i=0;i<=x.length;i++){
//do something
}

据我所写如下:
@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class})
public class test{
@Test
public void junk(){

PowerMockito.mockStatic(System.class);
PowerMockito.when( System.getenv("values"))).thenReturn("ab,cd");
}

}

在调试时,我在 for 循环行中得到空指针。在代码库中检查 System.getenv("values") 时,仍然发现它为空

请赞成决议

编辑:
确切的问题可复制场景:
package com.xyz.service.impl;

public class Junkclass {
public String tests(){
String xx[] = System.getenv("values").split(",");
for (int i = 0; i < xx.length; i++) {
return xx[i];
}
return null;
}
}

package com.xyz.service.impl
@InjectMocks
@Autowired
Junkclass jclass;

@Test
public void junk() {
String x = "ab,cd";

PowerMockito.mockStatic(System.class);

// establish an expectation on System.getenv("values")
PowerMockito.when(System.getenv("values")).thenReturn(x);

// invoke System.getenv("values") and assert that your expectation was applied correctly
Assert.assertEquals(x, System.getenv("values"));
jclass.tests();

}

最佳答案

在您的测试用例中,您正在调用 System.getenv("values").split(",") 但您没有告诉 PowerMock 从 System.getenv("values") 返回任何内容,因此您的代码在尝试对来自 split(",") 的空响应调用 System.getenv("values") 时将抛出 NPE。

我不清楚您测试的目的,但以下测试将通过,并显示如何在 System.getenv("values") 上设置期望值:

@Test
public void junk() {
String input = "ab,cd";

PowerMockito.mockStatic(System.class);

// establish an expectation on System.getenv("values")
PowerMockito.when(System.getenv("values")).thenReturn(input);

// invoke System.getenv("values") and assert that your expectation was applied correctly
Assert.assertEquals(input, System.getenv("values"));

String x[] = System.getenv("values").split(",");
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
}

上面的代码会打印出:
ab
cd

更新 :

基于上述问题中“精确场景”的规定,以下测试将通过,即 System.getenv("values")junkclass.tests() 中调用时将返回模拟值......
@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class, junkclass.class})
public class Wtf {

@Test
public void junk() {
String x = "ab,cd";

PowerMockito.mockStatic(System.class);

// establish an expectation on System.getenv("values")
PowerMockito.when(System.getenv("values")).thenReturn(x);

// invoke System.getenv("values") and assert that your expectation was applied correctly
Assert.assertEquals(x, System.getenv("values"));
jclass.tests();
}
}

关于PowerMockito+Junit - 模拟 System.getenv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980464/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com