【问题标题】:AbstractClass Junit with Autowired annotation具有自动装配注释的抽象类 Junit
【发布时间】:2018-09-13 10:23:06
【问题描述】:

我有一个在其中使用@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。

【问题讨论】:

  • 你在模拟一个类并期望它是自动连接的......那是行不通的。

标签: java spring junit mocking mockito


【解决方案1】:

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

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

使用

@InjectMocks
private AbstractAdminSearchService mock;

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

【讨论】:

  • 是的,没错,但是我的抽象类有一个具体的方法,那么我们如何Junit呢?
  • 我们可以在为子类编写Junit的同时覆盖抽象类中的具体方法
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多