Unit testing: Call @PostConstruct after defining mocked behaviour

前端 未结 2 1332
没有蜡笔的小新
没有蜡笔的小新 2021-01-08 00:09

I have two classes:

public MyService {
    @Autowired
    private MyDao myDao;     
    private List list; 

    @PostConstruct
    private void         


        
2条回答
  •  伪装坚强ぢ
    2021-01-08 00:47

    I have same kind of requirement in my project. where i need to set a string using @PostConstructor and I did not want to ran spring context or in other words I want simple mock. My requirement was follow:

    public class MyService {
    
    @Autowired
    private SomeBean bean;
    
    private String status;
    
    @PostConstruct
    private void init() {
        status = someBean.getStatus();
    } 
    

    }

    Solution:

    public class MyServiceTest(){
    
    @InjectMocks
    private MyService target;
    
    @Mock
    private SomeBean mockBean;
    
    @Before
    public void setUp() throws NoSuchMethodException,  InvocationTargetException, IllegalAccessException {
    
        MockitoAnnotations.initMocks(this);
    
        when(mockBean.getStatus()).thenReturn("http://test");
    
        //call post-constructor
        Method postConstruct =  MyService.class.getDeclaredMethod("init",null); // methodName,parameters
        postConstruct.setAccessible(true);
        postConstruct.invoke(target);
      }
    
    }
    

提交回复
热议问题