首页 > 解决方案 > 带有 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。

标签: javaspringjunitmockingmockito

解决方案


基本上我们不会为抽象类写Junit,因为我们不能为它们创建对象,如果是普通的具体类而不是下面的代码

mock=Mockito.mock(AbstractAdminSearchService.class,
Mockito.CALLS_REAL_METHODS);

利用

@InjectMocks
private AbstractAdminSearchService mock;

然后所有的模拟将被插入到真实的对象中


推荐阅读