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)
1
  • Can you please provide your pom.xml of all the modules(A, B, and parent)? Commented Dec 24, 2020 at 13:12

1 Answer 1

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;

//...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.