1

尝试使用 AspectJ LTW 来实现具有面向方面的测试的 DDD 架构,该测试访问数据库并检查用户是否存在...

目前我面临两个问题,我不知道这个类是否被注入到 Spring 上下文中。我试图添加

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath*:EntityTest-context.xml"})

没有成功。这是我要运行的测试。如果您注意到我正在 @Before 上创建 EntityManager,我不知道这是否是正确的用法,因为当我尝试查找创建的对象时,我会返回 null。

package ienterprise.common.aspects;

import ienterprise.common.model.CompanyPosition;
import ienterprise.common.model.InternalUser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

import static org.junit.Assert.assertEquals;
import org.springframework.test.context.ContextConfiguration;

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath*:EntityTest-context.xml"})
public class EntityTest {

    private static final Logger logger = LoggerFactory.getLogger(EntityTest.class);

//    @PersistenceContext(unitName="mysql") // FIXME inject this in unit tests
    private static EntityManager manager;

    @Before
    public void setUp(){
        EntityManagerFactory mngFactory = Persistence.createEntityManagerFactory("mysql");
        manager = mngFactory.createEntityManager();
    }

    @Test
    public void createUser(){

        InternalUser someGuy = new InternalUser();

        someGuy.setName("Adam");
        someGuy.setUser("Engineer");

        someGuy.create();

        logger.debug("created user: {}", someGuy);
        //FIXME: Can't find the user in the database.
        InternalUser foundUser = manager.find(InternalUser.class, 1L);

        logger.debug("fetched user: {}",foundUser);


        assertEquals( someGuy, foundUser);
    }
}

我们的上下文 xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:load-time-weaver/>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
    </bean>
</beans>

如何删除 @Before 并注入 PersistenceContext?

如何确保我的班级有 Spring Context?

这对我来说都是新东西,如果有这种 Spring+Hibernate+AspectJ+JUnit 设置,我会很感激一些到 github 存储库的链接。

如果有不清楚的地方或需要额外的细节,请告诉我。

4

0 回答 0