Search code examples
javamavenspring-bootmockitojunit4

Spring Boot problem with JUnit execution test


I have the problem with running Junit test, I have error :

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:73)

How I see, Spring Boot can not find my test Class. I have multiple maven modules, in my A module I have SpringBootApplication class and controllers and in module B I have my Service module were I wrote my Test Class:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestClass{

    @Autowired
    private ImplDatabase serviceDatabase;

    @MockBean
    private Repository repository;

    @Test
    public void saveMethode() {
        Model model= new Model ();

        event.setCreated(LocalDateTime.now());
        model.setMessage("sdsd");
        model.setCategory("Somi");

        when(repository.save(model)).thenReturn(model);
        assertEquals(model, serviceDatabase.saveTest(model));
    }

}

And I have C module where is stored my Repository.

Hierarchy of dependency is: I have dependency in A module for B and C, and in B module I have dependency for C.


Solution

  • In module B you can create

    @ComponentScan({"com.mycompany.myapp.moduleB",
                    "com.mycompany.myapp.moduleB.subpackage1",
                    "com.mycompany.myapp.moduleB.subpackage1.subsubpackage1a",
                    "com.mycompany.myapp.moduleB.subpackage2"
                     /*add here all required packages to scan for B's components and services*/ })
    public class BConfig {}
    

    and then mark Junit test in module B with @SpringBootTest(classes = BConfig.class)

    Note, BConfig does not have to be in main sources, place it in test sources