如何在Spring Roo中使用JUnit测试?(EntityManager的问题)

Eri*_*son 6 java junit entitymanager spring-roo

我正在尝试为Spring Roo项目编写JUnit测试.如果我的测试需要使用实体类,我会得到以下异常:

java.lang.IllegalStateException: Entity manager has not been injected 
(is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
Run Code Online (Sandbox Code Playgroud)

Spring Aspects JAR看起来配置正确.特别是,我在pom.xml文件中有以下内容:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>${spring.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

<plugin>
  <configuration>
  <outxml>true</outxml>
  <aspectLibraries>
    <aspectLibrary>
      <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </aspectLibrary>
  </aspectLibraries>
  <source>1.6</source>
  <target>1.6</target>
  </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

当没有从JUnit测试调用时,使用实体类的类工作正常.知道如何设置,以便从JUnit测试中注入实体管理器吗?

这是我的Test类(或多或少):

public class ServiceExampleTest {

  @Test
  public void testFoo() {
    FooService fs = new FooServiceImpl();
    Set<Foo> foos = fs.getFoos();
  }
}
Run Code Online (Sandbox Code Playgroud)

这足以抛出异常.FooServiceImpl类返回一个Foo,其中Foo是一个实体类.该getFoos()应用程序时,通常的方式运行方法的工作.问题只出在单元测试的背景下.

小智 6

ponzao是对的.通过让我的测试类扩展AbstractJunit4SpringContextTests,我能够拥有所有弹簧注入魔法.

例如

@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
public class SelfRegistrationTest extends AbstractJUnit4SpringContextTests {
Run Code Online (Sandbox Code Playgroud)


Ada*_*ent 3

这是 Spring Roo 的一个非常烦人的问题,我还没有找到官方的解决方案。

但是......这里有两个解决方法:

  • 将 spring-aspects jar 复制到您的项目,然后将其添加到您的项目 AspectJ Aspect Path
  • 使用 Maven 运行单元测试(并错过绿条 :( )

对于选项一,右键单击您的项目,选择 Properties-> AspectJ Build -> Aspect Path Tab。