Search code examples
spring-bootjunit4spring-boot-testmulti-module

Unit test in multi-module spring boot project


I have multi-module project with similar structure as below:

  • server (which includes Application Context Configuration) and other configurations
  • shared (Utility classes used by other modules)
  • service (module with various repository and services)
  • transaction (module which handles transaction) I need to write test for the project but I cannot change the project structure. I created a test in my transaction module.

First I got

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

I solved it by Creating a @Configuration file in the test folder like so

@Configuration
@ComponentScan("com.mohen")
public class TestConfig {
}

And then I used it in the @SpringBootTest(TestConfig.class) .I was able to autowire, the IDE did not show any sign of error. But when I run my tests I get NoSuchBeanDefinitionException from a different class that is trying to autowire a dependency from the service module.

How to solve these issues?

The main configuration file of the application looks like

@SpringBootApplication(scanBasePackages = "com.mohen")
@EnableScheduling
@EnableAsync
@Import(value = {SSIpFilter.class, MainConfig.class})
public class Application extends SpringBootServletInitializer {...}

The MainConfig.class contains componentScan and Import annotation.

If I try to Import the MainConfig.class in my test I get a suggestion to add a dependency to the server module, which I would not want to do.

Also the entire application uses a single property file (yml). Where should I keep my property file for the test?

EDIT

I managed to run the tests, a dataJpaTest and an integration test, but it loads the entire application context.

Now the problem is, the tests that pass normally , fail when I build my project ./gradlew clean build

I get

java.lang.NoClassDefFoundError

in some classes and

Caused by: javassist.NotFoundException

in other.

I have tried adding the javaassist library but it doesn't work.

Any idea?


Solution

  • I found the solution to my question. Due to the project being multi module, the classes and the packages were not being recognized by other modules. I made a few changes in my build.gradle files of the modules.

    testRuntime project(':shared')
    

    I added the above in the dependencies and also added

    jar {
        enabled = true
    }
    bootRepackage{
        enabled = false
    }
    

    The jar creates a simple non executable jar file while the bootRepackage disables the creation of an executable jar which by default is its nature.