[英]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. 在spring boot的一个简单的mvc应用程序中,我想对称为LibraryService(接口)和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
. 我们可以看到它依赖于类
MediaLibraryDetail
。 Also, ObjectId
is another class which is type of its parameter libraryId
. 同样,
ObjectId
是另一个类,它是其参数libraryId
类型。
I want to do unit testing in spring boot for method getLibraryById()
. 我想在春季启动中对方法
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));
我在最后一行上收到此错误
java.lang.NullPointerException
assertSame(mediaLibraryDetail,libraryService.getLibraryById(libraryId));
Where am I wrong ? 我哪里错了?
And if you use it that way? 如果您以这种方式使用它?
@Mock
private LibraryDAOImpl libDao;
@Mock
private ObjectId libraryId;
@InjectMocks
private LibraryServiceImpl libraryService;
Expanding on KLHauser's answer, I'd replace the @InjectMocks annotation (which isn't needed) with a @Spy annotation. 扩展KLHauser的答案,我将@InpyMocks注释(不需要)替换为@Spy注释。
That way you can check whether method on the Dao/repository actually has been called that you expected to be called: 这样,您可以检查Dao /存储库上的方法是否实际上已被调用,而您预期会被调用:
verify(libDay).getLibraryById(libraryId);
Here's what you need to do: 这是您需要做的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.