Number945
Number945

Reputation: 4950

java.lang.NullPointerException in Unit Testing spring service class

In a simple mvc application in spring boot , I want to do unit testing of a class of service layer called LibraryService (interface) and LibraryServiceImpl.

public interface LibraryService {

    /*
     * Returns media library object given the library object id.
     */
    public MediaLibraryDetail getLibraryById(ObjectId libraryId);
}

Below we see it's implementation

@Service
public class LibraryServiceImpl implements LibraryService {

    @Autowired
    private LibraryDAOImpl libDao;


    @Override
    public MediaLibraryDetail getLibraryById(ObjectId libraryId) {
        return libDao.getLibraryById(libraryId);
    }
}

We can see it has dependency on a class MediaLibraryDetail. Also, ObjectId is another class which is type of its parameter libraryId.

I want to do unit testing in spring boot for method getLibraryById().

Here's is my code:

@RunWith(MockitoJUnitRunner.class)
public class LibraryServiceImplTest {

    @Mock
    private LibraryDAO libDao = new LibraryDAOImpl();
    @Mock
    private ObjectId libraryId;
    @InjectMocks
    private  LibraryService libraryService =new LibraryServiceImpl();


    @Test
    public void getLibraryByIdTest(){

    MediaLibraryDetail mediaLibraryDetail =new MediaLibraryDetail();
    mediaLibraryDetail.setCollectionName("abc");

    when(libDao.getLibraryById(libraryId)).thenReturn(mediaLibraryDetail);
    assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));

    }
}

I am getting this error java.lang.NullPointerException on this last line assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));

Where am I wrong ?

Upvotes: 0

Views: 4306

Answers (3)

jwenting
jwenting

Reputation: 5663

Expanding on KLHauser's answer, I'd replace the @InjectMocks annotation (which isn't needed) with a @Spy annotation.

That way you can check whether method on the Dao/repository actually has been called that you expected to be called:

verify(libDay).getLibraryById(libraryId);

Upvotes: 1

KLHauser
KLHauser

Reputation: 876

And if you use it that way?

@Mock
private LibraryDAOImpl libDao;
@Mock
private ObjectId libraryId;
@InjectMocks
private LibraryServiceImpl libraryService;

Upvotes: 2

Durlabh Sharma
Durlabh Sharma

Reputation: 407

Here's what you need to do:

Get Rid of @InjectMocks

Upvotes: 0

Related Questions