我在课堂上尝试模仿的那行是:
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");
}
}
在调试时,我在循环行中获得了空指针。在代码库中检查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();
}
答案 0 :(得分:3)
在您的测试用例中,您正在调用System.getenv("values").split(",")
,但是您没有告诉PowerMock从System.getenv("values")
返回任何内容,因此您的代码在尝试调用split(",")
时会抛出NPE。 System.getenv("values")
的响应为空。
我不清楚您测试的目的,但以下测试将通过,它显示了如何对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();
}
}