5

I have two Grails Projects in Eclipse. I am referencing one project inside the other with the Configure Build Path setup. Running tests however throws an error java.lang.IllegalStateException: Method on class [com.example.domain.Phone] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

Normally this is fixed with a @Mock (using Mockito) or mockDomain(), but I am not in a unit test so these items are not seen.

How can I test my service layer through an integration test if it cannot see my domain objects that I need to use? These domain objects are separated because of the need to use them across multiple projects.

bdparrish
  • 3,216
  • 3
  • 37
  • 58

3 Answers3

2

If your GORM classes are not in the same package as your Application class then you need to add the ComponentScan annotation to the Application class to indicate where you GORM classes are. Example:

@ComponentScan(basePackages=['foo.bar', 'my.company'])
class Application {
....
Graeme Rocher
  • 7,985
  • 2
  • 26
  • 37
1

If you are writing tests do not forget:

  1. Annotations in Spec. @IntegrationTest is important

    @ContextConfiguration(loader = SpringApplicationContextLoader, classes = ConfigTest)
    @EnableAutoConfiguration
    @IntegrationTest
    class PaymentServiceSpec extends Specification{
      // Tests with GORM entities
    }
    
  2. Class where hibernate is injected

    @SpringBootApplication
    @Import(HibernateGormAutoConfiguration)
    class CoreConfigTest {
    }
    
  3. Because of @IntegrationTest it is necessary to have an Application class for tests

    @SpringBootApplication
    class TestApplication {
      static void main(String[] args) {
        run TestApplication, args
      }
    }
    

I am using this dependencies:

  runtime 'org.postgresql:postgresql:9.3-1102-jdbc41'

  compile("org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE") {
      exclude module: 'spring-boot-cli'
      exclude module: 'groovy-all'
    }

  compile("org.springframework.boot:spring-boot-starter-jdbc:1.2.2.RELEASE")
tsunllly
  • 1,568
  • 1
  • 13
  • 15
0

There is GORM for Spring Boot available. Examples in https://spring.io/guides/gs/accessing-data-gorm/

If you are writing tests, you can use the HibernateTestMixin or use HibernateDatastoreSpringInitializer to initialize GORM.

Lari Hotari
  • 5,190
  • 1
  • 36
  • 43
  • 1
    I'm in the same situation. I already configured an external application using Spring boot and GORM, using Groovy entities packaged as a Jar file. However, Spring boot also complains that the entities are being used outside of a Grails application. If I put them inside the same java package as the application, then it works. Why? :P. Thanks! – Jesús Zazueta Nov 27 '14 at 19:27