3

I have a multi-module project where only the root module has a class with @SpringBootApplication. Other modules are added to the POM file of root module as dependencies. To test other modules I created a module (let's call it test-module) with @SpringBootApplication annotated class and other test classes to run the spring context in modules tests. I added test-module as a dependency to other modules, but spring context doesn't run when I run tests with maven. How to add it correctly?

project structure:

---> root (this module starts spring context)
|
|--- moduleA
|
|--- moduleB

I want to test moduleA and moduleB, so I created a test-module with required dependencies and class with @SpringBootApplication annotation

|--- test-module (module with @SpringBootApplication)
|
|---> moduleA (test-module as dependency in test scope)
|
|---> moduleB (test-module as dependency in test scope)
asdfasdf
  • 45
  • 3

1 Answers1

0

If your module has no @SpringBootApplication, you should use @ContextConfiguration instead of @SpringBootTest in junit test code.

Firstly, you define a class under /src/test, maybe called 'TestConfig', using @Configuration and @ComponentScan import the beans you want to test.

Secondly, you use @ContextConfiguration(classes = {TestConfig.class}) in header of junit test.

The below is sample code:

TestConfig.java

@Configuration
@ComponentScan(basePackages = {"com.xxx"}) // base package of module or what package you want to import. you can write more ones if there are more than one package.
public class TestConfig {
}

Junit Test

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class TestServiceA {

    @Autowired
    public ServiceA serviceA;

//...
}
jacky-neo
  • 763
  • 4
  • 7