我创建了一个Maven项目,当我通过eclipse运行项目的所有单元测试时,所有这些都按预期传递。但是,当我通过终端进行mvn install
时,我发现测试testPredictThrowsException()
出现以下错误:
testPredictThrowsException(com.ner.core.NamedEntityRecognizerTest) Time elapsed: 0.001 sec <<< ERROR!
java.lang.NullPointerException
at com.ner.core.NamedEntityRecognizer.train(NamedEntityRecognizer.java:70)
at com.ner.core.NamedEntityRecognizerTest.setUp(NamedEntityRecognizerTest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
...这意味着我在ner
setUp()方法中实例化的对象@Before
没有被运行,导致它被设置为null。这是测试和POM.xml。想法?
public class NamedEntityRecognizerTest {
NamedEntityRecognizer ner;
@Before
public void setUp() throws NamedEntityRecognizerException {
ner = new NamedEntityRecognizer();
InputStream trainingStream = NamedEntityRecognizerTest.class.getClassLoader().getResourceAsStream("trainingData1.train");
ner.train(trainingStream);
}
@Test(expected=NamedEntityRecognizerException.class)
public void testPredictThrowsException() throws NamedEntityRecognizerException {
System.out.println("NERRRR: " + ner);
ner.predict(null);
}
}
的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ner</groupId>
<artifactId>AmpelloNER</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>AmpelloNER</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<!-- more dependencies go here... -->
</dependency>
</dependencies>
</project>
更新
当我尝试获取test/resources/
目录中文件的绝对路径时,我发现NullPointerException被抛出(参见下面的代码)。当我通过eclipse运行测试时,它能够找到该文件,但是,当我尝试通过键入mvn install
来通过终端运行它时,它会抛出NullPointerException
。我该如何解决这个问题?
@Before
public void setUp() throws NamedEntityRecognizerException {
ner = new NamedEntityRecognizer();
String trainingFile = NamedEntityRecognizerTest.class.getClassLoader().getResourceAsStream("trainingData1.train");
ner.train(trainingFile); // <<<---- This throws the NPE
}