Spring JUnit: How to Mock autowired component in autowired component

前端 未结 6 1523
花落未央
花落未央 2020-12-02 12:20

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

6条回答
  •  醉话见心
    2020-12-02 12:31

    You could use Mockito. I am not sure with PostConstruct specifically, but this generally works:

    // Create a mock of Resource to change its behaviour for testing
    @Mock
    private Resource resource;
    
    // Testing instance, mocked `resource` should be injected here 
    @InjectMocks
    @Resource
    private TestedClass testedClass;
    
    @Before
    public void setUp() throws Exception {
        // Initialize mocks created above
        MockitoAnnotations.initMocks(this);
        // Change behaviour of `resource`
        when(resource.getSomething()).thenReturn("Foo");   
    }
    

提交回复
热议问题