【发布时间】:2017-10-23 16:10:06
【问题描述】:
我是编程世界的新手,所以我说的话可能看起来很傻。
我正在尝试在 Eclipse 下以 JUnit 的身份运行 spring-boot 测试,但我只是不知道如何使用 spring-boot 注释......我已经阅读了几个指南并浏览了这个网站但没有找到任何能解决我问题的东西。
我正在尝试运行下面的 JUnit 测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={CBusiness.class,CService.class,CDao.class}, loader = AnnotationConfigContextLoader.class)
@SpringBootTest
public class CalculTest {
@Autowired
CBusiness business;
@Test
public void testCalcul() throws TechnicalException {
Object object= new Object();
object.setId1("00");
object.setId2("01");
object.setNombrePlacesMaximum(new BigInteger("50"));
Long result=business.calcul(object);
assertTrue(result>0);
}
将此作为 JUnit 测试运行会给我以下异常:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
CDao 类中的 EntityManager 参数具有注释 @PersistenceContext,我认为这意味着它是由 Hibernate 自动生成的,但显然它不是......我如何仅使用 java 代码来实例化 EntityManager?我没有任何 .xml 或 .properties 文件...
仅供参考,这里是测试调用的类:
业务层:
@Component("cBusiness")
public class CBusiness {
@Autowired
CService cService;
public long calcul(Object object) throws TechnicalException {
//Code (calls a method from CService class)
}
服务层:
@Service
public class CService {
@Autowired
CDao cDao;
道层
@Repository
@Transactional(rollbackFor = {TechnicalException.class})
public class CDao {
@PersistenceContext
EntityManager entityManager;
我尝试仅使用业务层上的 @autowire 注释在 Web 服务中测试该方法,如果工作正常,但我无法在 JUnit 测试中实例化它。我尝试了几种运行此测试的方法,但我不确定这是正确的方法,因此我愿意接受任何建议。
提前致谢。
【问题讨论】:
-
Remove
@ContextConfiguration... Spring Boot 会为你做检测... -
我试过了,但现在我有以下异常: java.lang.IllegalStateException: 无法加载 ApplicationContext 原因:java.lang.IllegalArgumentException: LoggerFactory 不是 Logback LoggerContext 但 Logback 在类路径上.删除 Logback 或竞争实现(从文件加载的类 org.slf4j.helpers.NOPLoggerFactory:/D:/m2repo/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar)。如果您使用的是 WebLogic,则需要将“org.slf4j”添加到 WEB-INF/weblogic.xml 中的首选应用程序包中:org.slf4j.helpers.NOPLoggerFactory
-
你读过那个堆栈跟踪吗?您的依赖项有问题...
-
确实,解决依赖问题解决了它。我的测试现在运行良好,非常感谢!
标签: java eclipse spring-boot junit