Gunnar Eketrapp
Gunnar Eketrapp

Reputation: 2149

Spring Junit and annotation based autowiring

I added a junit test to a simple spring example but it fails to autowire the json service that I wrote.

What is needed to get autowiring to work in a spring JUnit tests?

To try the failing project out do ...

git clone https://bitbucket.org/oakstair/spring-boot-cucumber-example
cd spring-boot-cucumber-example
./gradlew test

Thanks in advance!

Application

@SpringBootApplication
@ComponentScan("demo")
public class DemoApplication extends SpringBootServletInitializer {

Service interface

@Service
public interface JsonUtils {

    <T> T fromJson(String json, Class<T> clazz);

    String toJson(Object object);

}

Service implementation

@Component
public class JsonUtilsJacksonImpl implements JsonUtils {

Test

    @ContextConfiguration()
    @RunWith(SpringJUnit4ClassRunner.class)
    @ComponentScan("demo")
    public class JsonUtilsTest {

       @Autowired
        private JsonUtils jsn;

Upvotes: 0

Views: 566

Answers (3)

thebytewalker
thebytewalker

Reputation: 346

Add @SpringBootTest

On your test class And provide your SpringBootApplication class and Json utils class to the classes field of @SpringBootTest

It should look like this

@ContextConfiguration()
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={<package>.DemoApplication.class, <package>.JsonUtil.class } )
@ComponentScan("demo")
public class JsonUtilsTest {

Upvotes: 0

Gunnar Eketrapp
Gunnar Eketrapp

Reputation: 2149

Adding this to the test class fixed my problems!

@ContextConfiguration(classes = {DemoApplication.class})

Upvotes: 0

Plog
Plog

Reputation: 9622

In your JsonUtilsTest you can't put a @ComponentScan on the class level here since it isn't a @Configuration class. With a @ContextConfiguration annotation like you are using here it is first looking for a static inner @Configuration class so add one of those with the @ComponentScan and it should work:

@ContextConfiguration()
@RunWith(SpringJUnit4ClassRunner.class)
public class JsonUtilsTest {

    @Autowired
    private JsonUtils jsn;


    @Test
    // Note: This test is not tested since I haven't got autowiring to work.
    public void fromJson() throws Exception {
        Integer i = jsn.fromJson("12", Integer.class);
        assertEquals(12, (int) i);
    }

    @Test
    // Note: This test is not tested since I haven't got autowiring to work.
    public void toJson() throws Exception {
        assertEquals("12", jsn.toJson(new Integer(12)));
    }

    @Configuration
    @ComponentScan("demo")
    public static class TestConfiguration {
    }

}

EDIT: Or you can make Spring boot do the work for you by using the @SpringBootTest annotation with a SpringRunner instead:

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

Upvotes: 1

Related Questions