Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JUnit tests with Spring Roo? (Problems with EntityManager)

I'm trying to write a JUnit test for a Spring Roo project. If my test requires use of the entity classes, I get the following Exception:

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

The Spring Aspects JAR looks to be configured correctly. In particular, I have the following in the pom.xml file:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>${spring.version}</version>
</dependency>

and

<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>

and the classes that use the entity classes work fine, when not called from a JUnit test. Any idea how I can set things up so that the Entity manager is injected from a JUnit test?

Here is my Test class (more or less):

public class ServiceExampleTest {

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

This is enough to throw the exception. The FooServiceImpl class returns a Set of Foo, where Foo is an entity class. The getFoos() method works when the application is run in the usual way. The problem only comes in the context of unit tests.

like image 719
Eric Wilson Avatar asked Jul 19 '10 19:07

Eric Wilson


2 Answers

ponzao is correct. I am able to have all the spring injection magic by having my test class extend AbstractJunit4SpringContextTests.

e.g.

@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
public class SelfRegistrationTest extends AbstractJUnit4SpringContextTests {
like image 80
ddabber Avatar answered Sep 22 '22 05:09

ddabber


This is an incredibly annoying problem with Spring Roo and I have not figured out the official solution for.

But ... here are two workarounds:

  • Copy the spring-aspects jar to your project then add it to your Projects AspectJ Aspect Path
  • Use Maven to run your unit tests (and miss the green bar :( )

For option one Right click on your project select Properties-> AspectJ Build -> Aspect Path Tab.

like image 37
Adam Gent Avatar answered Sep 26 '22 05:09

Adam Gent