Unit testing with SpringJUnit4ClassRunner using only @Component and @Autowired

2k views Asked by At

I have the following class:

@Component
public class MyClass {
    @Autowired MyPojo pojo;
}

How do i test it without mocking the injected beans? I do not have a configuration [XML or declarative]. I have done the following:

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan
public class MyClassTest {
    @Autowired MyClass myClass;

    @Test
    public void test() {
        this.myClass...()
    }
}
1

There are 1 answers

1
frenchu On BEST ANSWER

If you do not want use any type of configuration, neither Java nor XML config, you can use @ContextConfiguration with your component classes listed:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MyPojo.class, MyClass.class })
public class MyClassTest {

    @Autowired 
    private MyClass myClass;

    @Test
    public void test() {
        // myClass...
    }
}

Please note that MyPojo class should also be annotated with @Component.

However, in the real life scenario you probably will need at least one @Configuration class (which can be also used with @ContextConfiguration).

Please refer Spring Documentation for more information about Spring integration tests support.