如何使用Powermock验证内部方法调用?

时间:2018-09-11 06:33:50

标签: junit mockito powermockito

我正在尝试使用PowerMockito通过验证内部的 audit()方法调用来测试保存方法。 此内部调用由 auditor 对象进行,该对象正在类的 init()方法中实例化。由于未注入,因此我将无法直接对其进行模拟。当我使用Mockito进行验证时,始终会说“与该模拟的交互为零”。 问:如何精确测试保存功能?请帮忙!

public class DaoImpl implements Dao{
private Auditor auditor;

@InjectValue
private ObjectLoader loader;

@InjectValue
private ConfigurationProvider confProvider;

@PostConstruct
public void init() {
    //Mock this object instantiation and verify audit is called once
    auditor = new SyncAuditor(confProvider.getClientConfiguration(), new EventRegProvider());
}

@Override
public void save(final AuditEvt auditEvt) {
  final AuditedEvent auditedEvent = builder.build();
  auditor.audit(auditedEvent); 
 }

测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ DaoImplTest.class })
@PowerMockIgnore("javax.management.*")
public class DaoImplTest extends PowerMockito {

@InjectMocks
private DaoImpl dataAccess;

@Mock
private SynchAuditor auditorMock;
 @Before
public void setUp() throws Exception {
    loader = ObjectLoader.init("JUNIT");
    loader.bind(ConfigurationProvider.class, configurationProviderMock);
    dataAccess = loader.newInstance(DaoImpl.class);
}

@After
public void tearDown() {
    loader.release(dataAccess);
    ConnectionMgr.disconnect("JUNIT");
}

@Test
public void testSaveAuditEvent() throws Exception { 
     PowerMockito.whenNew(SynchAuditor.class).
     withArguments(Matchers.any(ClientConfiguration.class), Matchers.any(EventRegProvider.class)).thenReturn(this.auditorMock);
     final AuditEvent event = AuditEvent.from(null, "principal", UUID.randomUUID().toString(), "randomText",
            new AuditEvtDefn((long) 522, "234242", "234242fdgd", true), SUCCESS, null, new GregorianCalendar());
     dataAccess.save(event);
     Mockito.verify(auditorMock, times(1)).audit(Matchers.any(AuditedEvent.class));
}

即使PowerMockito.verifyNew表示互动为零 PowerMockito.verifyNew(SynchronousAuditor.class,times(1)).withArguments(Matchers.any(AuditorClientConfiguration.class),Matchers.any(EventRegistrationProvider.class));

1 个答案:

答案 0 :(得分:0)

因此,我发现Java反射将在这种情况下有所帮助。您将必须抓住真实对象,然后将模拟对象设置为真实对象。

version

现在,验证将成功运行。

0