下面列出了org.mockito.Mockito#clearInvocations ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void verifyThatKeyIsCached() throws InterruptedException, TimeoutException, ExecutionException {
mockSuccessfulDiscoveryEndpointRequest();
mockSuccessfulPublicKeysRequest();
final Optional<PublicKey> publicKeyFromEndpoint =
underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS);
assertThat(publicKeyFromEndpoint).isNotEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
final Optional<PublicKey> publicKeyFromCache =
underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS);
assertThat(publicKeyFromCache).contains(publicKeyFromEndpoint.get());
assertThat(publicKeyFromCache).isNotEmpty();
verifyNoMoreInteractions(httpClientMock);
}
@Test
public void verifyThatKeyIsNotCachedOnErrorResponseFromDiscoveryEndpoint() {
mockErrorDiscoveryEndpointRequest();
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS))
.withCauseExactlyInstanceOf(GatewayAuthenticationProviderUnavailableException.class);
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock, never()).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS))
.withCauseExactlyInstanceOf(GatewayAuthenticationProviderUnavailableException.class);
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock, never()).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
}
@Test
public void verifyThatKeyIsNotCachedIfResponseDoesNotContainKeyId()
throws InterruptedException, ExecutionException, TimeoutException {
mockSuccessfulDiscoveryEndpointRequest();
mockSuccessfulPublicKeysRequestWithoutMatchingKeyId();
assertThat(underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS)).isEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
Mockito.clearInvocations(httpClientMock);
assertThat(underTest.getPublicKey("google.com", KEY_ID).get(LATCH_TIMEOUT, TimeUnit.SECONDS)).isEmpty();
verify(httpClientMock).createSingleHttpRequest(DISCOVERY_ENDPOINT_REQUEST);
verify(httpClientMock).createSingleHttpRequest(PUBLIC_KEYS_REQUEST);
}
@Test
public void shouldReconnectIfSocketIsClosed() {
new TestKit(actorSystem) {{
final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
final Connection connection =
TestConstants.createConnection(randomConnectionId, new Target[0])
.toBuilder()
.uri("amqps://username:[email protected]:65536") // port 65536 does not even exist ;)
.build();
final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);
final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));
whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
getRef());
expectMsgClass(Status.Failure.class);
thenExpectCleanupResourcesCalled();
Mockito.clearInvocations(delegate);
thenExpectCleanupResourcesCalledAfterTimeout(
connectivityConfig.getClientConfig().getConnectingMinTimeout());
thenExpectNoConnectClientCalled();
}};
}
@Test
public void doesNotReconnectIfConnectionSuccessful() {
new TestKit(actorSystem) {{
final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
final Connection connection =
TestConstants.createConnection(randomConnectionId, new Target[0]);
final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);
final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));
whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
getRef());
thenExpectConnectClientCalled();
Mockito.clearInvocations(delegate);
andConnectionSuccessful(dummyClientActor, getRef());
expectMsgClass(Status.Success.class);
thenExpectNoConnectClientCalledAfterTimeout(connectivityConfig.getClientConfig().getConnectingMinTimeout());
}};
}
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);
}
@Test
void should_ReturnDefinitionEntity_When_ConvertingWorkbasketToDefinition()
throws NotAuthorizedException, WorkbasketNotFoundException {
WorkbasketImpl workbasket = (WorkbasketImpl) workbasketService.newWorkbasket("1", "DOMAIN_A");
String id = "ID1";
workbasket.setId(id);
List<WorkbasketAccessItem> workbasketAccessItems =
Arrays.asList(
workbasketService.newWorkbasketAccessItem(id, "a"),
workbasketService.newWorkbasketAccessItem(id, "b"));
WorkbasketImpl target1 = (WorkbasketImpl) workbasketService.newWorkbasket("2", "DOMAIN_A");
WorkbasketImpl target2 = (WorkbasketImpl) workbasketService.newWorkbasket("3", "DOMAIN_A");
target1.setId("target1");
target2.setId("target2");
List<WorkbasketSummary> workbasketSummaries = Arrays.asList(target1, target2);
Mockito.doReturn(workbasketAccessItems).when(workbasketService).getWorkbasketAccessItems(id);
Mockito.doReturn(workbasketSummaries).when(workbasketService).getDistributionTargets(id);
Object[] mocks = {workbasketService, workbasketAssembler, accessItemAssembler};
Mockito.clearInvocations(mocks);
WorkbasketDefinitionRepresentationModel repModel = assembler.toModel(workbasket);
assertThat(repModel).isNotNull();
// workbasketAssembler does the conversion. Thus no further testing needed.
assertThat(repModel.getWorkbasket()).isNotNull();
// accessItemAssembler does the conversion. Thus no further testing needed.
assertThat(repModel.getAuthorizations()).hasSize(2);
assertThat(repModel.getDistributionTargets()).containsExactlyInAnyOrder("target1", "target2");
InOrder inOrder = Mockito.inOrder(mocks);
inOrder.verify(workbasketAssembler).toModel(workbasket);
inOrder.verify(workbasketService).getWorkbasketAccessItems(id);
inOrder.verify(accessItemAssembler).toCollectionModel(workbasketAccessItems);
inOrder.verify(accessItemAssembler, times(2)).toModel(any());
inOrder.verify(workbasketService).getDistributionTargets(id);
inOrder.verifyNoMoreInteractions();
Mockito.verifyNoMoreInteractions(mocks);
}
@Test
public void connectsAutomaticallyAfterActorStart() {
new TestKit(actorSystem) {{
final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
final Connection connection =
TestConstants.createConnection(randomConnectionId, new Target[0]);
final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);
final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));
thenExpectConnectClientCalledAfterTimeout(Duration.ofSeconds(5L));
Mockito.clearInvocations(delegate);
andConnectionSuccessful(dummyClientActor, getRef());
}};
}
@Parameters(method = "parametersFortestAccountCliParseAndRun")
@Test
public void testAccountCliParseAndRun(String[] options, ReturnType expected ){
CommandLine commandLine = new CommandLine(Arguments.class).addSubcommand(EditCli.class);
ParseResult result;
try{
result = commandLine.parseArgs(options);
}catch (Exception e){
if (expected.equals(ERROR)) {
return;
}
else {
throw e;
}
}
CommandSpec commandSpec = Cli.findCommandSpec(result, AccountCli.class);
//noinspection ConstantConditions
AccountCli spiedAccountCLI = spy((AccountCli) commandSpec.userObject());
doReturn(true).when(spiedAccountCLI).exportPrivateKey(anyString(),any());
doReturn(true).when(spiedAccountCLI).listAccounts();
doReturn(true).when(spiedAccountCLI).createAccount(any());
doReturn(true).when(spiedAccountCLI).importPrivateKey(anyString(), any());
doCallRealMethod().when(spiedAccountCLI).runCommand(any());
assertThat(spiedAccountCLI.runCommand(mockpr)).isEqualTo(expected);
if (spiedAccountCLI.getList()) {
verify(spiedAccountCLI, times(1)).listAccounts();
} else {
verify(spiedAccountCLI, times(0)).listAccounts();
}
if (!spiedAccountCLI.getGroup().getImportAcc().isEmpty()) {
verify(spiedAccountCLI, times(1)).importPrivateKey(anyString(), any());
} else {
verify(spiedAccountCLI, times(0)).importPrivateKey(anyString(),any());
}
if (!spiedAccountCLI.getGroup().getExport().isEmpty()) {
verify(spiedAccountCLI, times(1)).exportPrivateKey(anyString(),any());
} else {
verify(spiedAccountCLI, times(0)).exportPrivateKey(anyString(), any());
}
if (spiedAccountCLI.getGroup().getCreate()) {
verify(spiedAccountCLI, times(1)).createAccount(any());
} else {
verify(spiedAccountCLI, times(0)).createAccount(any());
}
Mockito.clearInvocations(spiedAccountCLI);
}
@Test
public void testFeatureTemplate() throws Throwable {
MainActivity activity = activityRule.getActivity();
FeatureFragment fragment = new FeatureFragment();
fragment.toastManager = Mockito.mock(ToastManager.class);
fragment.presenter = new FeatureFragmentPresenter();
FeatureManager featureManager = Mockito.mock(FeatureManager.class);
fragment.presenter.featureManager = featureManager;
Mockito.when(featureManager.loadData()).thenReturn(Observable.error(new Exception("error")));
activity.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_content_container, fragment)
.commit();
Espresso.onView(ViewMatchers.withId(R.id.feature_loader))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Mockito.verify(fragment.toastManager, VerificationModeFactory.times(1)).makeToast(Mockito.any(), Mockito.eq("error"), Mockito.any(), Mockito.anyInt());
ArrayList<FeatureModel> models = new ArrayList<>();
models.add(new FeatureModel());
models.add(new FeatureModel());
models.add(new FeatureModel());
Mockito.when(featureManager.loadData()).thenReturn(Observable.fromIterable(models).delay(3, TimeUnit.SECONDS));
Mockito.when(fragment.toastManager.makeToast(Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyInt()))
.thenThrow(new IllegalStateException("Error should not apprend"));
Espresso.onView(ViewMatchers.withId(R.id.feature_retry))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
.perform(ViewActions.click())
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Espresso.onView(ViewMatchers.withId(R.id.feature_loader))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Espresso.onView(ViewMatchers.withId(R.id.feature_rv))
.perform(RecyclerViewActions.actionOnItemAtPosition(2, ViewActions.click()));
Mockito.clearInvocations(featureManager);
Mockito.verify(featureManager, VerificationModeFactory.noMoreInteractions()).loadData();
activityRule.runOnUiThread(fragment::reload);
Espresso.onIdle();
}