NeplatnyUdaj NeplatnyUdaj - 5 months ago 38
Java Question

Spring JUnit: How to Mock autowired component in autowired component

I've got a Spring component I'd like to test and this component has an autowired attribute which I need to change for the purpose of unit testing. The problem is, that the class uses the autowired component inside the post-construct method so I'm not able to replace it(i.e. via ReflectionTestUtils) before it's actually used.

How should I do that?

This is the class I want to test:

public final class TestedClass{

private Resource resource;

private void init(){
//I need this to return different result

And this is the base of a test case:

@ContextConfiguration(locations= "classpath:applicationContext.xml")
public class TestedClassTest{

private TestedClass instance;

private void setUp(){
//this doesn't work because it's executed after the bean is instantiated
ReflectionTestUtils.setField(instance, "resource", new Resource("something"));

Is there some way to replace the resource with something else before the postconstruct method is invoked? Like to tell Spring JUnit runner to autowire different instance?

ph. ph.

You can provide a new testContext.xml in which the @Autowired bean you define is of the type you need for your test.