我正在尝试使用powermock测试一个方法。我还没有编写任何测试用例。我只是想把这门课准备好。以下是目前为止的内容:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ReadRubric.class })
public class ReadRubricTest {
@Before
public void setUp() throws Exception {
PowerMockito.mock(ReadRubric.class);
}
@After
public void tearDown() throws Exception {
}
@Test
public void invalidFile() throws Exception {
}
}
当我尝试运行此测试时,我得到以下错误。
java.lang.VerifyError: Bad type on operand stack in arraylength
Exception Details:
Location:
com/cerner/devcenter/wag/processor/ReadRubric.readRubric()Ljava/util/List; @809: arraylength
Reason:
Invalid type: 'java/lang/Object' (current frame, stack[0])
Current Frame:
bci: @809
flags: { }
locals: { 'java/util/ArrayList', 'au/com/bytecode/opencsv/CSVReader', top, top, '[Ljava/lang/String;', 'com/cerner/devcenter/wag/processor/Rule', 'java/lang/Object', 'java/lang/Object', top, top, top, top, top, top, top, 'java/lang/Object' }
stack: { 'java/lang/Object' }
java -version on cmd gives me 1.7.0_65
java_home is set to C:Program FilesJavajdk1.7.0_65
On eclipse I am using jre 7 and the compiler level is 1.7
在我的maven中,我添加了以下依赖项,以允许接受字符串而不是字符的切换情况:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
谁能帮我解决这个问题?下面是我要测试的方法:
public static List<Rule> readRubric() throws WAGException, IOException {
List<Rule> ruleList = new ArrayList<Rule>();
CSVReader rubricReader = null;
File file = new File(RUBRIC_FILE_NAME);
FileReader fileReader = new FileReader(file);
rubricReader = new CSVReader(fileReader);
String[] ruleRecord = null;
//rubricReader.readNext();
while ((ruleRecord = rubricReader.readNext()) != null) {
Rule rule = new Rule();
rule.setRuleName(ruleRecord[0].trim());
String parameters[] = ruleRecord[1].split(",");
rule.addParameter(Arrays.asList(parameters));
rule.setPoints(Integer.parseInt(ruleRecord[2].trim()));
rule.setRuleEngine(ruleRecord[3].trim());
rule.setComment(ruleRecord[4].trim());
ruleList.add(rule);
}
rubricReader.close();
return ruleList;
}
我在网上找到了解决方案:它说我需要在运行测试时将-XX:-UseSplitVerifier
添加到我的VM参数中。当我这样做时,测试运行。但是我需要它与maven一起运行,因为解决方案说我需要添加以下插件到maven:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<argLine>-XX:-UseSplitVerifier</argLine>
</configuration>
</plugin>
</plugins>
但是即使在我的POM中添加了这个,这个特殊的测试还是失败了。链接到解决方案
所以在工作了几个小时之后,我找到了问题的根本原因。在Java 7u65中,他们使字节码验证器更加严格,结果,字节码验证器正在读取PowerMock字节码并抛出VerifyError。基本上,PowerMock的字节码没有传递字节码验证器。唯一的方法是将-XX:-UseSplitVerifier
添加为VM参数或切换到Java 6。
在我的情况下,当我删除ruleRecord[1].split(",")
和当我实现我自己的分裂功能,测试工作得很好。我猜Powermock在我们使用时弄乱了字节码,例如像whenNew()
这样的方法。