kandarp
kandarp

Reputation: 1101

How to mock method of Injected service in Spring Integration Tests

I have following service class, that I want to test

@Service
public class MasterService {

    @Inject
    private ServiceOne serviceOne;

    @Autowired
    private ServiceTwo serviceTwo;

    @Inject
    private ServiceThree serviceThree;

    @VisibleForTesting
    void execute() {
        if (serviceThree.isFlag()) {
           ....
        }
    }

I am testing execute() method. I want to mock serviceThree.isFlag() to return true. Following is my test.

    public class MasterServiceIT{

        @Inject
        private MasterService masterService;

        @Inject
        private ServiceThree serviceThree;

        @Test
        public void testMasterService() {
            when(serviceThree.isFlag()).thenReturn(true); <---- this never works 
            masterService.execute();
        }
    }

However, it never retrieves true. Any remarks? I wanted to use @InjectMocks Then can I inject only this service which I mocked? or I need to mock each service if I am using @InjectMocks

Upvotes: 0

Views: 763

Answers (1)

Daimon Cool
Daimon Cool

Reputation: 98

Are you sure that you need to mock for an integration test? Well, sometimes there are cases when we need to mock some service which refers to some external services like SharePoint, etc. Well if you need to mock so in this case you need to mock spring service bean in spring context. You can do it via @MockBean

Upvotes: 2

Related Questions