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...()
    }
}
1
  • What do you want to do in that test() function. Please elaborate Commented Jun 5, 2018 at 11:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.