Andrunevchyn

Andrunevchyn


February 2019
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728  

Categories


@SpringBootTest

Andriy AndrunevchynAndriy Andrunevchyn

Sometimes I hate springboot for different kind of hidden things. You just copy sample with dozens different annotations and then it doesn’t work and you have no any idea  what is wrong ’cause you don’t see any logs about that

So shortly – if you try to configure test suite for SpringBoot pay attention you  cannot just easily follow SpringBoot spec

According to spec

package hello;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Test
    public void contextLoads() throws Exception {
    }

}

and most probably it will work for you (not sure) but in my case I decided to work with junit5 so my code was

package hello;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ApplicationTest {

    @Test
    public void contextLoads() throws Exception {
    }

}

And as you already understood It didn’t work. After some time I figured out @SpringBootTest annotation required dedicated test spring config file at least in my case

package hello;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { TestWebConfig.class })
public class ApplicationTest {

    @Test
    public void contextLoads() throws Exception {
    }

}
package hello;
@EnableWebMvc
@Configuration
@ComponentScan("hello")
public class TestWebConfig implements WebMvcConfigurer {

}

I hope it will help somebody.
P.S.
SpringBoot version 2.2.0.BUILD-SNAPSHOT so maybe it’s some some changes on snapshot
P.P.S. Thx to one smart guy I found a reason. Main source package should be the same as a package of main class with annotation @SpringBootApplication, otherwise annotation @SpringBootTest doesn’t work properly without defining config file. Also I would recommend do not move Main class from root package if you don’t want to break some autoconfiguration features

andriy@andrunevchyn.com

Comments 0
There are currently no comments.