我试图在课堂上嘲笑的路线是:
String x[] = System.getenv("values").split(",")
for(int i=0;i<=x.length;i++){
//do something
}
Run Code Online (Sandbox Code Playgroud)
据我所写如下:
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
在调试时,我在 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();
}
Run Code Online (Sandbox Code Playgroud)
gly*_*ing 11
在您的测试用例中,您正在调用,System.getenv("values").split(",")但您没有告诉 PowerMock 从中返回任何内容,System.getenv("values")因此您的代码在尝试调用split(",")来自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]);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码会打印出:
ab
cd
Run Code Online (Sandbox Code Playgroud)
更新:
基于上述问题中“确切场景”的规定,以下测试将通过,即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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12939 次 |
| 最近记录: |