Sam
Sam

Reputation: 513

Junit Mockito NullPointerException for Mock for constructor based autowiring

I'm trying to test the implementation class, in which I'm creating a constructor based autowiring for the Interface. I'm not suppose to change this class or the way it's autowired.

While writing test cases for the implementation class I'm getting NullPointerException because the object created in Implementation class has different object reference and the mock object has different reference value.

Could anyone please tell me how to mock the object.

Implementation class

public class ImplementationClass implements ClientClass {

private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
    this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;

@Autowired
BBB bbb;

@Autowired
CCC ccc;

public DomainClass getDetails( String Id ) {
    // aaa, bbb, ccc usage
    DomainClass getDetDocument =
        repositoryInterface.findById( Id ).orElse( null );

}

Unit Test Class

@Mock
RepositoryInterface repositoryInterface;

@Mock
DomainClass DomainClass;

@Mock
AAA aaa;

@Mock
BBB bbb;

@Mock
CCC ccc;

@InjectMocks
ImplementationClass implementationClass;

@Before
public void setUp() {
    MockitoAnnotations.initMocks( this );
    }

 @Test
public void getDetTest() {
DomainClass dc = new DomainClass();
    dc.setId( "Id-123456789" );
    dc.setDetailsList( <Some list> );

    Optional<DomainClass> c1 = Optional.of( dc );
    // when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
    DomainClass c2 = implementationClass.getDetails( "Id-123456789" );

    assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}

UPDATE : While debugging the Test class, the object repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 ); creates a reference value (23425634534@2005) and when the ImplementationClass is called the repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null ); in ImplementationClass has a reference value (23425634534@1879). Because of this I'm getting null for getDetDocument.

Upvotes: 2

Views: 2752

Answers (1)

Sam
Sam

Reputation: 513

After all the research, got it working by changing the way the constructor was creating the object.

// @Mock //removed this annotation
   RepositoryInterface repositoryInterface;


@Before
   public void setUp() {
     repositoryInterface = mock(RepositoryInterface.class)
     ImplementationClass = new ImplementationClass(repositoryInterface);
     MockitoAnnotations.initMocks( this );
}

Reference : https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html

Upvotes: 3

Related Questions