Home > Blockchain >  Pass real object and mock object in constructor
Pass real object and mock object in constructor

Time:07-20

I have a AccountDetails constructor as below.

private final AccountDetailsRestClient accountDetailsRestClient;
private final ConstantMapService constantMapService; 

private CalculationMap calculationMap;

public AccountDetails(final AccountDetailsRestClient accountDetailsRestClient, final ConstantMapService constantMapService) {
    this.accountDetailsRestClient = accountDetailsRestClient;
    this.constantMapService = constantMapService;
    initializeConstantsData();
}

private void initializeConstantsData() {
    if (this.calculationMap == null) {
        this.calculationMap = constantMapService.getMap(java.time.LocalDate.now());
    }
}

Using Mockito I am unable to initialize all 3 objects accountDetailsRestClient, constantMapService, calculationMap. If accountDetailsRestClient is not null then constantMapService is null or vice versa.

Mockito test class:

@RunWith(MockitoJUnitRunner.class)
    public class AccountDetailsTest {
    
        @Mock
        private AccountDetailsRestClient accountDetailsRestClient;
    
        @Mock(answer = RETURNS_DEEP_STUBS)
        private CalculationMap calculationMap;
    
        @InjectMocks
        private final AccountDetails sut = new AccountDetailsTestImpl(new ConstantMapServiceMock());

       @Test
        public void testMethod() {
            //left it blank to check constructor issue first
        }
    
        class AccountDetailsTestImpl extends AccountDetails {
            AccountDetailsTestImpl(final ConstantMapService constantMapService) {
                    super(accountDetailsRestClient, constantMapService);
                }
            }
    
    }

But the accountDetailsRestClient is now null in the constructor.

How can I solve this issue without using PowerMock. Either by changing the code in the class or by changing the mockito test class?

CodePudding user response:

Don't use @InjectMocks and simply do things by hand, like you almost are already:

AccountDetails sut = new AccountDetails(mockDependency, realObject);

Since @Mock and similar auto-wiring have to happen after the class is instantiated, if you need to refer to a mock during initialization, create it programmatically:

AccountDetailsRestClient mockRestClient = mock(AccountDetailsRestClient.class);
  • Related