0

I want to run some lines of code before this line runs:

@Autowired
private SomeClass a;

I'm working on a testing class, I tried @Before, but the @Autowired runs before the code in the @Before, so there is another solution to run code before the autowiring is happening?

This is the code:

Test class:

private classX x;

@Mock
private classA a;

@Autowired
private classB b;

@Before
private void setUpMockResponse() {
    when(a.getMeB()).thenReturn(b);
}

classX code:

// Constructor of classX class.
public classX(classA a) {
    this.a = a;
    this.b = a.getMeB();
}

If there is any solution to the problem I would be happy to see, the problem is that i need the code in the setUpMockResponse to happen before the autowiring to the classX happens because in the constructor i get b from method on a which is a mock so i need to first set a response when calling the method getMeB(), and also i need b to be autowired.

T.S
  • 911
  • 8
  • 24
  • Are you using JUnit ? and which is the code that you want execute before ? Please post it as it may do a difference whether this codes requires or doesn't require the Spring Context. – davidxxx Nov 06 '17 at 17:12
  • Wich os the testes class? – bpedroso Nov 08 '17 at 00:44
  • I don't understand the question, I edited my question and gave more details about the problem and what i want to do. – T.S Nov 08 '17 at 07:00

1 Answers1

0

Sounds like a bad idea to me but who am I to judge? If you want to run code before a dependency is injected, I would write your own setter method and put the @Autowried on the setter, then putting the code before the assignment within the setter:

@Autowired
public void setA(A a)
{
    // TODO - put code here
    this.a = a;
}

Other option is putting this in an aspect for the setter.

Please note I don't recommend any of these options just trying to answer your question, doing this sort of stuff leads to torturing the next poor soul that comes across this. You won't always need to use Spring in your tests hopefully.

Derrops
  • 7,651
  • 5
  • 30
  • 60
  • Do you have another solution? I edited my question with more details. – T.S Nov 08 '17 at 07:00
  • I think you are going to have to elaborate more on what you are wanting to achieve. Not really sure what your use case is. – Derrops Nov 09 '17 at 02:56