Testing @Postconstruct with Mockito

20,716

Solution 1

Because PostConstruct is only spring concept. But you can call postConstruct manually.

@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
    this.service.init(); //your Injected bean
}

Solution 2

I modified a little your service by adding a method foo:

@Service
public class MyService {
    public MyService() {
        System.out.println("CONSTRUKTOR");
    }

    @PostConstruct
    public void init() {
        System.out.println("POST CONSTRUCT");
    }

    public String foo() {
        return "bar";
    }
}

If you want to get behaviour, that you described, there are at least two possibilities:

  1. @RunWith(SpringJUnit4ClassRunner.class) + @Autowired - that combination will let you to get a usual service in your test

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = MyService.class)
    public class Mockito1 {
    
        @Autowired
        private MyService service;
    
        @Before
        public void init() {
        }
    
        @Test
        public void name() throws Exception {
            System.out.println(service.foo());
        }
    }
    

This code will print:

CONSTRUKTOR
POST CONSTRUCT
bar
  1. @RunWith(SpringJUnit4ClassRunner.class) + @SpyBean - that combination will let you to get a service in your test and to modify it's behaviour using Mockito

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = MyService.class)
    public class Mockito1 {
    
        @SpyBean
        private MyService service;
    
        @Before
        public void init() {
        }
    
        @Test
        public void name() throws Exception {
            System.out.println(service.foo());
            Mockito.when(service.foo()).thenReturn("FOO");
            System.out.println(service.foo());
        }
    }
    

This code will print:

CONSTRUKTOR
POST CONSTRUCT
bar
FOO
Share:
20,716
Jan Testowy
Author by

Jan Testowy

Updated on November 19, 2020

Comments

  • Jan Testowy
    Jan Testowy over 3 years

    Why when I injecting mocks via Mockito my @Postconstruckt method is not calling?

    @Service
    public class MyService {
        public MyService() {
            System.out.println("CONSTRUKTOR");
        }
    
        @PostConstruct
        public void init() {
            System.out.println("POST CONSTRUCT");
        }
    
    @RunWith(MockitoJUnitRunner.class)
    public class Mockito1 {
    
        @InjectMocks
        private MyService service;
    
        @Before
        public void init() {
        }
    

    Output: Only: CONSTRUKTOR

  • M. Deinum
    M. Deinum over 5 years
    @PostConstruct isn't only a spring concept, it isn't even a Spring annotation.