当尝试从 Eclipse 开始我的 JUnit-Test 时,我得到一个“ClassNotFoundException”。从控制台运行“mvn test”时 - 一切正常。此外,Eclipse 中没有报告任何问题。
我的项目结构如下:
- 父项目(pom-packaging)
- Web 项目(war-packaging - 我的 JUnit-test 在这里)
- 弹性项目
- 配置项目
编辑:怎么找不到课程?这是一个没有特殊库的简单 HelloWorld 应用程序。
这是我的 JUnit 的运行配置: 替代文本 http://www.walkner.biz/_temp/runconfig.png
测试类(但正如我所说;它也不适用于简单的 HelloWorld ……):
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;
public class UserDaoTest {
/**
* the applicationcontext.
*/
private ApplicationContext ctx = null;
/**
* the user itself.
*/
private User record = null;
/**
* Interface for the user.
*/
private UserRepository dao = null;
@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}
@After
public void tearDown() throws Exception {
dao = null;
}
@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}
@Test
public final void testIsNoUser() throws Exception {
Assert.assertFalse(dao.isUser("not", "existing"));
Assert.assertFalse(dao.isUser(null, null));
Assert.assertFalse(dao.isUser("", ""));
}
}
原文由 swalkner 发布,翻译遵循 CC BY-SA 4.0 许可协议
这种情况我遇到过好几次,经过多次尝试,我找到了解决办法。
检查您的项目构建路径并为每个文件夹启用特定的输出文件夹。 逐一检查项目的每个源文件夹,并设置 Maven 将使用的输出文件夹。
例如,您的 web 项目的
src/main/java
应该有target/classes
在 web 项目下,测试类应该有target/test-classes
也在 web 项目下等等。使用此配置将允许您在 Eclipse 中执行单元测试。
还有一个建议,如果您的 Web 项目的测试需要资源下的一些配置文件,请确保将该文件夹作为源文件夹包含在内,并进行正确的构建路径配置。
希望能帮助到你。