在spring boot的一个简单的mvc应用程序中,我想对称为LibraryService(接口)和LibraryServiceImpl的服务层类进行单元测试。
public interface LibraryService {
/*
* Returns media library object given the library object id.
*/
public MediaLibraryDetail getLibraryById(ObjectId libraryId);
}
下面我们看到它的实现
@Service
public class LibraryServiceImpl implements LibraryService {
@Autowired
private LibraryDAOImpl libDao;
@Override
public MediaLibraryDetail getLibraryById(ObjectId libraryId) {
return libDao.getLibraryById(libraryId);
}
}
我们可以看到它依赖于类
MediaLibraryDetail
。同样,ObjectId
是另一类,其类型为参数libraryId
。我想在Spring Boot中对方法
getLibraryById()
进行单元测试。这是我的代码:
@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));
}
}
我在最后一行
java.lang.NullPointerException
上收到此错误assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));
我哪里错了?
最佳答案
如果您以这种方式使用它?
@Mock
private LibraryDAOImpl libDao;
@Mock
private ObjectId libraryId;
@InjectMocks
private LibraryServiceImpl libraryService;