Easy layout: setting up wait inside @PostConstruct

I have a class that uses @PostConstruct to cache some objects.

@Component
public class A {

   @Autowired
   private B b;

   private X x;

   @PostConstruct 
   public void init(){
       x = b.doSomething()
   }

}

public class C {

   @Autowired
   private A; 
}


public class TestClass {

   @Autowired
   private A;

   @Before
   public init() {
       expect(b.dosomething()).andReturns(x);
   }

   @Test
   public test1() {
       //test
   }
}

I mocked B as it calls an HTTP call to get x. But when doing this through unit test, I get the following error:

Missing behaviour definition for the preceding method call:
B.dosomething().andXXX() 

Everything works fine if I do the same inside some normal class A method. I use spring to inject dependencies.

I think the reason for this behavior is because I set the wait on the layout of class B inside my unit test, which is called "after" this init method. How can I check this?

+4
source share
1 answer

"init" @PostConstruct A, , Spring . .

:

import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;

public class TestA {

    private A a = new A();
    private B b = EasyMock.createMock(B.class);

    @Before
    public void init() {
        Whitebox.setInternalState(a, "b", b);
    }

    @Test
    public void testInit() {
        EasyMock.reset(b);
        //define mock behavior here
        EasyMock.replay(b);

        a.init();

        //assert and verify
        EasyMock.verify(b);
    }
}
0

All Articles