java - 带有 Autowired 注释的 AbstractClass Junit
问题描述
我有一个在其中使用 @Autowired 注释的抽象类。我正在尝试使用 MockitoJUnitRunner 编写 junit。
@RunWith(MockitoJUnitRunner.class)
public class AbstractAdminSearchServiceTest {
@Mock
private IUPSService upsService;
Map<String,String> map;
@Before
public void setUp() {
map=new HashMap<>();
}
@Test
public void testSearchAdministratorsForIndividualNotification(){
AbstractAdminSearchService
mock=Mockito.mock(AbstractAdminSearchService.class,
Mockito.CALLS_REAL_METHODS);
when(upsService.getUsersProfile(buildUserIds(),new String[]
{})).thenReturn(map);
mock.searchAdministratorsForIndividualNotification(buildSolrUsers(),
"");
}
@Mock 不起作用,并且 'upsService' 没有被嘲笑。结果,当实际调用 upsService.getUsersProfile 时,我得到了 NullpointerException。
解决方案
基本上我们不会为抽象类写Junit,因为我们不能为它们创建对象,如果是普通的具体类而不是下面的代码
mock=Mockito.mock(AbstractAdminSearchService.class,
Mockito.CALLS_REAL_METHODS);
利用
@InjectMocks
private AbstractAdminSearchService mock;
然后所有的模拟将被插入到真实的对象中
推荐阅读
- docker - 奇怪的CouchDB错误,怎么理解?
- java - 使用 javaFX 根据操作系统计算窗口装饰的大小
- php - wp_mail 正在发送具有相同数据的消息
- c# - C# Ping.Send() 无限期,这会显着降低计算机速度
- javascript - 如果在页面上找到文本,JS IF 语句将应用 CSS 隐藏文本
- mean-stack - 如何使用 Sendgrid / MEAN Stack 发送放弃购物车电子邮件
- c++ - 尝试使用成员函数创建模板函数时遇到问题
- android - Ionic 3 / Angular 5 App 在(想要的)循环函数中崩溃
- ios - 无法转换类型“(
) -> Void' 到预期的参数类型 '(Either<[_]>) -> Void' - angular - 身份验证服务和登录组件未通信