PowerMock 是一个很棒的工具,我最近开始使用它来测试一些静态方法。不幸的是,我无法重写任何东西(除了测试),并且需要 PowerMock 能够严格按原样测试此代码。
这是我的 PowerMock 测试:
import java.io.*;
import org.junit.*;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({Solution.class})
public class SolutionTest {
// stream to record the output (System.out)
private ByteArrayOutputStream testOutput;
@Before
public void setUpOutputStream() {
testOutput = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOutput));
}
// input feed to Scanner (System.in)
private void setInput(String input) {
System.setIn(new ByteArrayInputStream(input.getBytes()));
}
@Test
public void test1() {
// set System.in
setInput("foo");
final String expected = "foobar";
final String actual = testOutput.toString();
// run the program (empty arguments array)
Solution.main(new String[0]);
assertEquals(expected, actual);
}
@Test
public void test2() {
setInput("new");
Solution.main(new String[0]);
final String expected = "newbar";
final String actual = testOutput.toString();
assertEquals(expected, actual);
}
}
PowerMock 使我可以在以下场景中对静态方法连续运行(并通过)两个测试:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
scanner.close();
System.out.print(input + "bar");
}
}
在 PowerMock 之前,我一直被异常所困扰(由于必须测试静态方法)java.lang.IllegalStateException: Scanner closed
但是,在这种调用第二个静态方法(scanner 也是静态成员)的替代方案中,该问题再次出现。
在这里,test1 会通过,但 test2 甚至无法运行,因为 java.lang.IllegalStateException: Scanner closed
我需要两个测试在后一种情况下都通过,就像在前一种情况下一样。
繁华开满天机
慕森卡
相关分类