[英]Cannot “Run File” from src\test folder -> main class not found or could not be loaded
[英]HtmlUnit - Class not found in src folder but run in test folder
我使用Maven / Eclipse在Java中编程。
从单元测试运行时,我能够正常运行HtmlUnit。 (测试/)
但是,当我尝试在src /文件夹中使用相同的代码时,我收到java.lang.NoClassDefFoundError
消息。 我能够解决它们的唯一方法是手动将所有jar添加到构建路径。 但这对我来说没有意义,因为jar文件显示在我的Maven依赖项中。
pom.xml(实际的pom文件中有更多的依赖项)
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.9</version>
<scope>test</scope>
</dependency>
HtmlUnit代码的Sample块
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(url);
System.out.println("Executing Pages JavaScript for " + config.executeJavaScriptTime + " seconds..."); webClient.waitForBackgroundJavaScript(config.executeJavaScriptTime);
dom = cleaner.clean(page.asXml());
html = cleaner.getInnerHtml(dom);
webClient.closeAllWindows();
有任何想法吗? 谢谢。
应用于依赖项的测试作用域意味着它在编译类路径中不可用。 这样,您发布的代码不依赖于测试代码。 可以在此处找到更完整的解释。 如果要构建的项目仅用于测试,则应删除scope标记以使其采用默认范围进行编译。 但总的来说,从src构建的运输代码不应该依赖于测试库JUnit是正确的。
截至目前,我发现唯一可行的工作是创建一个注释为@Test
的方法,并将爬虫作为JUnit测试运行。
即
public class Crawler() {
@Test
public void runAsTest() {
Crawler crawler = new Crawler();
String[] urls = new String[]{
"http://www.url.com/1",
"http://www.url.com/2",
"http://www.url.com/3"
};
crawler.crawl(urls);
try {
Thread.sleep(1000 * 60 * 15); // without this the unit test exits too early
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// the rest of the class definition
}
我希望能够从标准的主要方法运行它,即
public class Crawler() {
public static void main(String[] args) {
Crawler crawler = new Crawler();
String[] urls = new String[]{
"http://www.url.com/1",
"http://www.url.com/2",
"http://www.url.com/3"
};
crawler.crawl(urls);
try {
Thread.sleep(1000 * 60 * 15); // without this the unit test exits too early
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// the rest of the class definition
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.