0

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...()
    }
}
Akhil Alluri
  • 13
  • 1
  • 6

1 Answers1

3

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.

frenchu
  • 288
  • 3
  • 9
  • I ended up adding the classes to ContextConfiguration as you described. As it turns out, for my scenario i do not need a @configuration class as my use case works fine with just components and autowired. I do not have a use in this case for initialization beans. – Akhil Alluri Jun 07 '18 at 08:22