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

How to verify an internal method call using Powermock?

我正在尝试使用 PowerMockito 通过验证内部 audit() 方法调用来测试保存方法。 此内部调用由 auditor 对象进行,该对象在 class 的 init() 方法中实例化。因为它没有被注入,所以我不能直接模拟它。我用Mockito验证的时候总是说"There were zero interaction with the mock"。 Question:How 我到底要测试保存功能吗?请帮忙!

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));

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

final Field privateAuditorField = DaoImpl.class.getDeclaredField("auditor");
privateAuditorField.setAccessible(true);
privateAuditorField.set(dataAccess, auditorMock);

现在验证 运行 成功。

Mockito.verify(auditorMock, Mockito.times(1)).audit(Matchers.any(AuditedEvent.class));