下面列出了 io.netty.handler.codec.http2.Http2FrameWriter #org.mockito.verification.VerificationMode 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Wrapper around {@link Mockito#verify}, to keep log spam down on failure.
*/
private static <T> T verify(T mock, VerificationMode mode) {
try {
return Mockito.verify(mock, mode);
} catch (final AssertionError e) {
String msg = e.getMessage();
if (msg.length() >= 256) {
// AssertionError(String, Throwable) only present in Android API 19+
throw new AssertionError(msg.substring(0, 256)) {
@Override
public synchronized Throwable getCause() {
return e;
}
};
}
throw e;
}
}
/**
* Wait for the coordinator task to complete, and verify all the mocks
* @param op the {@link Subprocedure} to use
* @param prepare the mock prepare
* @param commit the mock commit
* @param cleanup the mock cleanup
* @param finish the mock finish
* @param opHasError the operation error state
* @throws Exception on unexpected failure
*/
private void waitAndVerifySubproc(Subprocedure op, VerificationMode prepare,
VerificationMode commit, VerificationMode cleanup, VerificationMode finish, boolean opHasError)
throws Exception {
boolean caughtError = false;
try {
op.waitForLocallyCompleted();
} catch (ForeignException fe) {
caughtError = true;
}
// make sure that the task called all the expected phases
Mockito.verify(op, prepare).acquireBarrier();
Mockito.verify(op, commit).insideBarrier();
// We cannot guarantee that cleanup has run so we don't check it.
assertEquals("Operation error state was unexpected", opHasError, op.getErrorCheckable()
.hasException());
assertEquals("Operation error state was unexpected", opHasError, caughtError);
}
@Override
public void verifyTriggerCallback(
Trigger<?, TimeWindow> mockTrigger,
VerificationMode verificationMode,
Long time,
TimeWindow window) throws Exception {
if (time == null && window == null) {
verify(mockTrigger, verificationMode).onEventTime(
anyLong(),
anyTimeWindow(),
anyTriggerContext());
} else if (time == null) {
verify(mockTrigger, verificationMode).onEventTime(
anyLong(),
eq(window),
anyTriggerContext());
} else if (window == null) {
verify(mockTrigger, verificationMode).onEventTime(
eq(time),
anyTimeWindow(),
anyTriggerContext());
} else {
verify(mockTrigger, verificationMode).onEventTime(
eq(time),
eq(window),
anyTriggerContext());
}
}
@Override
public void verifyTriggerCallback(
Trigger<?, TimeWindow> mockTrigger,
VerificationMode verificationMode,
Long time,
TimeWindow window) throws Exception {
if (time == null && window == null) {
verify(mockTrigger, verificationMode).onProcessingTime(
anyLong(),
anyTimeWindow(),
anyTriggerContext());
} else if (time == null) {
verify(mockTrigger, verificationMode).onProcessingTime(
anyLong(),
eq(window),
anyTriggerContext());
} else if (window == null) {
verify(mockTrigger, verificationMode).onProcessingTime(
eq(time),
anyTimeWindow(),
anyTriggerContext());
} else {
verify(mockTrigger, verificationMode).onProcessingTime(
eq(time),
eq(window),
anyTriggerContext());
}
}
private void verifyErrorMessageForParentJobLogLevel( LogLevel parentJobLogLevel, VerificationMode mode ) {
action.setLogMessage( "TEST" );
action.setEntryLogLevel( LogLevel.ERROR );
doReturn( parentJobLogLevel ).when( parentWorkflow ).getLogLevel();
action.setParentWorkflow( parentWorkflow );
ILogChannel logChannel = spy( action.createLogChannel() );
doReturn( logChannel ).when( action ).createLogChannel();
action.evaluate( new Result() );
verify( logChannel, mode ).logError( "TEST" + Const.CR );
}
@Override
public final ArgumentCaptor<P> executed(final VerificationMode verificationMode) {
try {
doVerify(verificationMode);
} catch (final Exception e) {
throw new RuntimeException(e);
}
return argumentCaptor;
}
public void verifyAddProjectAdapterCalls(VerificationMode times, VerificationMode confluenceTimes)
throws IOException, CreateProjectPreconditionException {
Mockito.verify(jenkinsPipelineAdapter, times).createPlatformProjects(isNotNull());
// check preconditions should be always called
Mockito.verify(bitbucketAdapter, times(1)).checkCreateProjectPreconditions(isNotNull());
Mockito.verify(bitbucketAdapter, times).createSCMProjectForODSProject(isNotNull());
Mockito.verify(bitbucketAdapter, times).createComponentRepositoriesForODSProject(isNotNull());
// jira components
Mockito.verify(jiraAdapter, times)
.createComponentsForProjectRepositories(isNotNull(), isNotNull());
Mockito.clearInvocations(
jiraAdapter, confluenceAdapter, bitbucketAdapter, jenkinsPipelineAdapter);
}
public <T> T verify(T mock, VerificationMode mode) {
if (mock == null) {
reporter.nullPassedToVerify();
} else if (!mockUtil.isMock(mock)) {
reporter.notAMockPassedToVerify(mock.getClass());
}
mockingProgress.verificationStarted(new MockAwareVerificationMode(mock, mode));
return mock;
}
private void verifySeenStatusReporter(VerificationMode verificationMode) throws InterruptedException {
String[] messageIds = {"1"};
mobileMessagingCore.setMessagesSeen(messageIds);
seenStatusReporter.sync();
verify(coreBroadcaster, verificationMode).seenStatusReported(any(String[].class));
}
protected Connection<String, String> assertNextConnection(SocketAddress host,
ConnectionFactory<String, String> cfMock,
ConnectionObservable<String, String> connectionObservable,
VerificationMode verificationMode) {
Connection<String, String> c = loadBalancerRule.connect(connectionObservable);
verify(cfMock, verificationMode).newConnection(host);
return c;
}
private void byteBufferWritten(final VerificationMode times)
{
try
{
verify(tcpChannel, times).write(byteBuffer);
reset(tcpChannel);
}
catch (final IOException e)
{
LangUtil.rethrowUnchecked(e);
}
}
private void savesInvalidMessage(
final int length, final VerificationMode mode, final MessageStatus status, final long timestamp)
{
verify(publication, mode).saveMessage(
anyBuffer(), eq(0), eq(length), eq(LIBRARY_ID),
anyLong(), anyLong(), anyInt(), eq(CONNECTION_ID),
eq(status), eq(0), eq(timestamp));
}
private void savesInvalidChecksumMessage(final VerificationMode mode)
{
verify(publication, mode).saveMessage(
anyBuffer(),
eq(0),
eq(INVALID_CHECKSUM_LEN),
eq(LIBRARY_ID),
eq(MESSAGE_TYPE),
anyLong(),
anyInt(),
eq(CONNECTION_ID),
eq(INVALID_CHECKSUM),
eq(0),
eq(TIMESTAMP));
}
@Override
public void verifyTriggerCallback(
Trigger<?, TimeWindow> mockTrigger,
VerificationMode verificationMode,
Long time,
TimeWindow window) throws Exception {
if (time == null && window == null) {
verify(mockTrigger, verificationMode).onEventTime(
anyLong(),
anyTimeWindow(),
anyTriggerContext());
} else if (time == null) {
verify(mockTrigger, verificationMode).onEventTime(
anyLong(),
eq(window),
anyTriggerContext());
} else if (window == null) {
verify(mockTrigger, verificationMode).onEventTime(
eq(time),
anyTimeWindow(),
anyTriggerContext());
} else {
verify(mockTrigger, verificationMode).onEventTime(
eq(time),
eq(window),
anyTriggerContext());
}
}
private void verifySessionsAcquired(final SessionState state, final VerificationMode times)
{
verify(gatewaySessions, times).acquire(
any(),
eq(state),
eq(false),
eq(HEARTBEAT_INTERVAL_IN_S),
anyInt(),
anyInt(),
any(),
any(),
any());
}
public <T> T verify(T mock, VerificationMode mode) {
if (!mocksToBeVerifiedInOrder.contains(mock)) {
reporter.inOrderRequiresFamiliarMock();
} else if (!(mode instanceof VerificationInOrderMode)) {
throw new MockitoException(mode.getClass().getSimpleName() + " is not implemented to work with InOrder");
}
return mockitoCore.verify(mock, new InOrderWrapper((VerificationInOrderMode) mode, this));
}
public VerificationMode pullVerificationMode() {
if (verificationMode == null) {
return null;
}
VerificationMode temp = verificationMode.getObject();
verificationMode = null;
return temp;
}
private void assertSentGapFill(
final int msgSeqNum,
final int newSeqNo,
final int offset,
final VerificationMode times)
{
verifyClaim();
assertResultBufferHasGapFillMessage(resultBuffer.capacity() - offset, msgSeqNum, newSeqNo);
verifyCommit(times);
}
static void verify(
final ErrorHandler mockErrorHandler,
final VerificationMode times,
final Class<? extends Throwable> exception)
{
try
{
Mockito.verify(mockErrorHandler, times).onError(any(exception));
}
finally
{
reset(mockErrorHandler);
}
}
private void verifyNewMetricDefinitionMessages(List<Alarm> alarms, final OutputCollector collector,
final MetricFilteringBolt bolt, VerificationMode howMany) {
for (final Alarm alarm : alarms) {
for (MetricDefinitionAndTenantId mtid : alarm.getAlarmedMetrics()) {
verify(collector, howMany)
.emit(MetricFilteringBolt.NEW_METRIC_FOR_ALARM_DEFINITION_STREAM, new Values(mtid, alarm.getAlarmDefinitionId()));
}
}
}
protected final Http2FrameWriter verifyWrite(VerificationMode verificationMode) {
return verify(frameWriter, verificationMode);
}
void verifyTriggerCallback(
Trigger<?, TimeWindow> mockTrigger,
VerificationMode verificationMode,
Long time,
TimeWindow window) throws Exception;
public VerificationMode pullVerificationMode() {
return threadSafely().pullVerificationMode();
}
public static VerificationMode atLeastOnce() {
return atLeast(1);
}
/**
* Common implementation of verification of static method calls.
*
* @param method The static method call to be verified
* @param mode The verification mode
* @param instanceInOrder If set, the {@link StaticInOrder} object
*/
@SuppressWarnings({"CheckReturnValue", "MockitoUsage", "unchecked"})
static void verifyInt(MockedVoidMethod method, VerificationMode mode, InOrder
instanceInOrder) {
if (onMethodCallDuringVerification.get() != null) {
throw new IllegalStateException("Verification is already in progress on this "
+ "thread.");
}
ArrayList<Method> verifications = new ArrayList<>();
/* Set up callback that is triggered when the next static method is called on this thread.
*
* This is necessary as we don't know which class the method will be called on. Once the
* call is intercepted this will
* 1. Remove all matchers (e.g. eq(), any()) from the matcher stack
* 2. Call verify on the marker for the class
* 3. Add the markers back to the stack
*/
onMethodCallDuringVerification.set((clazz, verifiedMethod) -> {
// TODO: O holy reflection! Let's hope we can integrate this better.
try {
ArgumentMatcherStorageImpl argMatcherStorage = (ArgumentMatcherStorageImpl)
mockingProgress().getArgumentMatcherStorage();
List<LocalizedMatcher> matchers;
// Matcher are called before verify, hence remove the from the storage
Method resetStackMethod
= argMatcherStorage.getClass().getDeclaredMethod("resetStack");
resetStackMethod.setAccessible(true);
matchers = (List<LocalizedMatcher>) resetStackMethod.invoke(argMatcherStorage);
if (instanceInOrder == null) {
verify(staticMockMarker(clazz), mode);
} else {
instanceInOrder.verify(staticMockMarker(clazz), mode);
}
// Add the matchers back after verify is called
Field matcherStackField
= argMatcherStorage.getClass().getDeclaredField("matcherStack");
matcherStackField.setAccessible(true);
Method pushMethod = matcherStackField.getType().getDeclaredMethod("push",
Object.class);
for (LocalizedMatcher matcher : matchers) {
pushMethod.invoke(matcherStackField.get(argMatcherStorage), matcher);
}
} catch (NoSuchFieldException | NoSuchMethodException | IllegalAccessException
| InvocationTargetException | ClassCastException e) {
throw new Error("Reflection failed. Do you use a compatible version of "
+ "mockito?", e);
}
verifications.add(verifiedMethod);
});
try {
try {
// Trigger the method call. This call will be intercepted and trigger the
// onMethodCallDuringVerification callback.
method.run();
} catch (Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
}
throw new RuntimeException(t);
}
if (verifications.isEmpty()) {
// Make sure something was intercepted
throw new IllegalArgumentException("Nothing was verified. Does the lambda call "
+ "a static method on a 'static' mock/spy ?");
} else if (verifications.size() > 1) {
// A lambda might call several methods. In this case it is not clear what should
// be verified. Hence throw an error.
throw new IllegalArgumentException("Multiple intercepted calls on methods "
+ verifications);
}
} finally {
onMethodCallDuringVerification.remove();
}
}
public MockAwareVerificationMode(Object mock, VerificationMode mode) {
this.mock = mock;
this.mode = mode;
}
public void verifyAddProjectAdapterCalls(VerificationMode times)
throws IOException, CreateProjectPreconditionException {
verifyAddProjectAdapterCalls(times, times);
}
public static VerificationMode only() {
return new Only(); //TODO make exception message nicer
}
@Override
public <T> T verify(T mock, VerificationMode mode) {
return instanceInOrder.verify(mock, mode);
}
private void verifySubscriptionsDeletedBySpace(List<String> deletedSpaces, VerificationMode verificationMode) {
for (String deletedSpace : deletedSpaces) {
verify(configurationSubscriptionQuery.spaceId(deletedSpace), verificationMode).delete();
}
}