org.mockito.Mockito#verifyZeroInteractions ( )源码实例Demo

下面列出了org.mockito.Mockito#verifyZeroInteractions ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void installWithNotification() {
    new DebugOverlay.Builder(mockApplication)
            .notification(false)
            .build()
            .install();

    new DebugOverlay.Builder(mockApplication)
            .notification(true)
            .build()
            .install();

    new DebugOverlay.Builder(mockApplication)
            .notification(true, "test")
            .build()
            .install();

    Mockito.verifyZeroInteractions(mockApplication);
}
 
@Test
@Description("Verify receiving a download_and_install message if a deployment is done with window configured and during maintenance window start time.")
@ExpectEvents({@Expect(type = TargetCreatedEvent.class, count = 1),
        @Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
        @Expect(type = ActionCreatedEvent.class, count = 1),
        @Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
        @Expect(type = SoftwareModuleUpdatedEvent.class, count = 6),
        @Expect(type = DistributionSetCreatedEvent.class, count = 1),
        @Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 2)})
public void receiveDownloadAndInstallMessageDuringMaintenanceWindow() {
    final String controllerId = TARGET_PREFIX + "receiveDownLoadAndInstallMessageDuringMaintenanceWindow";

    // setup
    registerAndAssertTargetWithExistingTenant(controllerId);
    final DistributionSet distributionSet = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
    testdataFactory.addSoftwareModuleMetadata(distributionSet);
    assignDistributionSetWithMaintenanceWindow(distributionSet.getId(), controllerId, getTestSchedule(-5),
            getTestDuration(10), getTestTimeZone());

    // test
    registerSameTargetAndAssertBasedOnVersion(controllerId, 1, TargetUpdateStatus.PENDING);

    // verify
    assertDownloadAndInstallMessage(distributionSet.getModules(), controllerId);
    Mockito.verifyZeroInteractions(getDeadletterListener());
}
 
@Test(groups = "unit")
public void onBeforeSendRequestNotInvoked() {
    RetryOptions retryOptions = new RetryOptions();
    GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class);

    Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false));
    ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(endpointManager, true, retryOptions);

    Exception exception = ReadTimeoutException.INSTANCE;

    RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName(
            OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Document);
    dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class);

    Single<IRetryPolicy.ShouldRetryResult> shouldRetry = clientRetryPolicy.shouldRetry(exception);
    validateSuccess(shouldRetry, ShouldRetryValidator.builder()
            .withException(exception)
            .shouldRetry(false)
            .build());

    Mockito.verifyZeroInteractions(endpointManager);
}
 
源代码4 项目: atlas   文件: AtlasCSRFPreventionFilterTest.java
@Test
public void testNoHeaderDefaultConfig_badRequest() throws ServletException, IOException {
	// CSRF has not been sent
	HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
	Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null);
	Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent);		

	// Objects to verify interactions based on request
	HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
	PrintWriter mockWriter = Mockito.mock(PrintWriter.class);
	Mockito.when(mockRes.getWriter()).thenReturn(mockWriter);
	FilterChain mockChain = Mockito.mock(FilterChain.class);

	// Object under test
	AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter();
	filter.doFilter(mockReq, mockRes, mockChain);

	verify(mockRes, atLeastOnce()).setStatus(HttpServletResponse.SC_BAD_REQUEST);
	Mockito.verifyZeroInteractions(mockChain);
}
 
源代码5 项目: samza   文件: TestLargeMessageSafeStore.java
@Test
public void testLargeMessagePutAllFailureWithDropLargeMessageDisabled() {
  LargeMessageSafeStore largeMessageSafeKeyValueStore = new LargeMessageSafeStore(store, storeName, false, maxMessageSize);
  byte[] key = new byte[16];
  byte[] largeMessage = new byte[maxMessageSize + 1];

  List<Entry<byte[], byte[]>> entries = new ArrayList<>();
  entries.add(new Entry<>(key, largeMessage));

  try {
    largeMessageSafeKeyValueStore.putAll(entries);
    Assert.fail("The test case should have failed due to a large message being passed to the changelog, but it didn't.");
  } catch (RecordTooLargeException e) {
    Mockito.verifyZeroInteractions(store);
  }
}
 
源代码6 项目: roboconf-platform   文件: MessagingMngrImplTest.java
@Test
public void testSendStoredMessages_NoMessageToSend() throws Exception {

	// sendStoredMessages is widely used in other tests.
	// We just complete the cases that are not covered.

	TestApplication app = new TestApplication();
	ManagedApplication ma = new ManagedApplication( app );

	app.getMySqlVm().setStatus( InstanceStatus.DEPLOYED_STARTED );
	Mockito.when( this.msgClient.isConnected()).thenReturn( true );

	Mockito.verifyZeroInteractions( this.msgClient );
	this.mngr.sendStoredMessages( ma, app.getMySqlVm());

	Mockito.verify( this.msgClient, Mockito.times( 1 )).isConnected();
	Mockito.verify( this.msgClient, Mockito.times( 0 )).sendMessageToAgent(
			Mockito.any( Application.class ),
			Mockito.any( Instance.class ),
			Mockito.any( Message.class ));
}
 
@Test
public void doNotLoadDevicesView() throws Exception {
    devices.load();

    source.set((SubsystemModel) Fixtures.loadModel("subsystems/lightsnswitches/subsystem_no_devs.json"));
    LightsNSwitchesDevListController.Callback callback = Mockito.mock(LightsNSwitchesDevListController.Callback.class);
    controller.setCallback(callback);

    Mockito.verifyZeroInteractions(callback);
}
 
@Test
@Description("Tests the download_only assignment: asserts correct dmf Message topic, and assigned DS")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
        @Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
        @Expect(type = ActionCreatedEvent.class, count = 1),
        @Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
        @Expect(type = SoftwareModuleUpdatedEvent.class, count = 6),
        @Expect(type = DistributionSetCreatedEvent.class, count = 1),
        @Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void downloadOnlyAssignmentSendsDownloadMessageTopic() {
    final String controllerId = TARGET_PREFIX + "registerTargets_1";
    final DistributionSet distributionSet = createTargetAndDistributionSetAndAssign(controllerId, DOWNLOAD_ONLY);

    final Message message = assertReplyMessageHeader(EventTopic.DOWNLOAD, controllerId);
    Mockito.verifyZeroInteractions(getDeadletterListener());

    assertThat(message).isNotNull();
    final Map<String, Object> headers = message.getMessageProperties().getHeaders();
    assertThat(headers).containsEntry("thingId", controllerId);
    assertThat(headers).containsEntry("type", EVENT.toString());
    assertThat(headers).containsEntry("topic", DOWNLOAD.toString());

    final Optional<Target> target = controllerManagement.getByControllerId(controllerId);
    assertThat(target).isPresent();

    // verify the DS was assigned to the Target
    final DistributionSet assignedDistributionSet = ((JpaTarget) target.get()).getAssignedDistributionSet();
    assertThat(assignedDistributionSet.getId()).isEqualTo(distributionSet.getId());
}
 
源代码9 项目: roboconf-platform   文件: RoboconfSchedulerTest.java
@Test
public void testStartAndStop() throws Exception {

	Assert.assertNull( this.scheduler.dmListener );
	Assert.assertNull( this.scheduler.scheduler );

	Mockito.verifyZeroInteractions( this.manager );
	this.scheduler.start();

	Assert.assertNotNull( this.scheduler.dmListener );
	Assert.assertNotNull( this.scheduler.scheduler );

	Assert.assertTrue( this.scheduler.scheduler.isStarted());
	Mockito.verify( this.manager, Mockito.times( 1 )).listenerAppears( this.scheduler.dmListener );
	Mockito.verify( this.manager, Mockito.atLeast( 1 )).configurationMngr();

	String dmPath = this.manager.configurationMngr().getWorkingDirectory().getAbsolutePath();
	String schedulerPath = this.scheduler.getSchedulerDirectory().getAbsolutePath();
	Assert.assertTrue( schedulerPath.startsWith( dmPath ));

	this.scheduler.stop();
	Mockito.verify( this.manager, Mockito.times( 1 )).listenerAppears( Mockito.any( IDmListener.class ));
	Mockito.verify( this.manager, Mockito.times( 1 )).listenerDisappears( Mockito.any( IDmListener.class ));

	Assert.assertNull( this.scheduler.dmListener );
	Assert.assertNull( this.scheduler.scheduler );
}
 
源代码10 项目: mapper   文件: TestEventDispatchThreadTest.java
@Test
public void simpleInvokeLaterWithDelay() {
  Runnable r = Mockito.mock(Runnable.class);
  edt.schedule(100, r);
  edt.executeUpdates();
  Mockito.verifyZeroInteractions(r);
  edt.executeUpdates(100);
  Mockito.verify(r).run();
}
 
@Test
public void testSetAudiencesIfSpecified_unspecified() throws Exception {
  annotationConfig.setAudiencesIfSpecified(null);
  Mockito.verifyZeroInteractions(config);

  String[] unspecified = {Api.UNSPECIFIED_STRING_FOR_LIST};
  annotationConfig.setAudiencesIfSpecified(unspecified);
  Mockito.verifyZeroInteractions(config);

  String[] audiences = {"bleh", "more bleh"};
  annotationConfig.setAudiencesIfSpecified(audiences);
  annotationConfig.setAudiencesIfSpecified(unspecified);
  Mockito.verify(config).setAudiences(Arrays.asList(audiences));
  Mockito.verifyNoMoreInteractions(config);
}
 
@Test
public void testDoFiler_withAuthentication_noCookie_corsEnabled() throws Exception {

	this.filter.setAuthenticationEnabled( true );
	this.filter.setAuthenticationManager( Mockito.mock( AuthenticationManager.class ));
	this.filter.setEnableCors( true );

	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	Mockito.when( req.getRequestURI()).thenReturn( "/whatever" );

	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );
	FilterChain chain = Mockito.mock( FilterChain.class );

	this.filter.doFilter( req, resp, chain );
	Mockito.verify( req ).getCookies();
	Mockito.verify( req, Mockito.times( 2 )).getRequestURI();
	Mockito.verify( req, Mockito.times( 2 )).getMethod();
	Mockito.verify( req ).getRemoteAddr();
	Mockito.verify( req ).getQueryString();
	Mockito.verify( req ).getHeader( ResponseCorsFilter.CORS_REQ_HEADERS );
	Mockito.verify( req ).getHeader( ResponseCorsFilter.ORIGIN );
	Mockito.verify( req ).getHeader( AuthenticationFilter.USER_AGENT );
	Mockito.verifyNoMoreInteractions( req );

	Mockito.verify( resp, Mockito.times( 3 )).setHeader( Mockito.anyString(), Mockito.anyString());
	Mockito.verify( resp ).sendError( 403, "Authentication is required." );
	Mockito.verifyNoMoreInteractions( resp );
	Mockito.verifyZeroInteractions( chain );

	Assert.assertEquals( 1, this.servletRegistrationComponent.getRestRequestsCount());
	Assert.assertEquals( 1, this.servletRegistrationComponent.getRestRequestsWithAuthFailureCount());
}
 
@Test
public void testExecute_invalidApplicationName() throws Exception {

	this.cmd.applicationName = "invalid";
	this.cmd.scopedInstancePath = null;

	ByteArrayOutputStream os = new ByteArrayOutputStream();
	this.cmd.out = new PrintStream( os, true, "UTF-8" );

	this.cmd.execute();
	Assert.assertTrue( os.toString( "UTF-8" ).contains( "Unknown application" ));
	Mockito.verify( this.applicationMngr, Mockito.times( 1 )).findManagedApplicationByName( this.cmd.applicationName );
	Mockito.verifyZeroInteractions( this.debugMngr );
}
 
源代码14 项目: wafer-java-server-sdk   文件: TunnelServiceTest.java
@Test
public void testPostBadRequest() throws JSONException, ConfigurationException {
	HttpMock httpMock = helper.createTunnelHttpMock("POST");
	httpMock.setRequestBody("illegal request");
	
	TunnelService service = new TunnelService(httpMock.request, httpMock.response);
	TunnelHandler handlerMock = mock(TunnelHandler.class);
	
	service.handle(handlerMock, null);
	
	Mockito.verifyZeroInteractions(handlerMock);
	assertFalse(helper.checkPostResponseSuccess(httpMock.getResponseText()));
}
 
源代码15 项目: besu   文件: BesuCommandTest.java
@Test
public void natManagerPodNameCannotBeUsedWithNatNoneMethod() {
  parseCommand("--nat-method", "NONE", "--Xnat-kube-pod-name", "besu-updated");
  Mockito.verifyZeroInteractions(mockRunnerBuilder);
  assertThat(commandOutput.toString()).isEmpty();
  assertThat(commandErrorOutput.toString())
      .contains(
          "The `--Xnat-kube-pod-name` parameter is only used in kubernetes mode. Either remove --Xnat-kube-pod-name or select the KUBERNETES mode (via --nat--method=KUBERNETES)");
}
 
@Test
public void testExecute_success() throws Exception {

	String txt = "Change status of /tomcat-vm/tomcat-server to DEPLOYED and STARTED";
	ChangeStateCommandExecution executor = buildExecutor( txt );

	Mockito.verifyZeroInteractions( this.instancesMngr );
	executor.execute();
	Mockito.verify( this.instancesMngr, Mockito.times( 1 )).changeInstanceState( this.ma, this.app.getTomcat(), InstanceStatus.DEPLOYED_STARTED );
}
 
@Test
public void updateContentNotify_withError() throws Exception {
    when(this.factory.checkCurrentSubfolder()).thenReturn(true);
    Mockito.doThrow(ApsSystemException.class).when(this.indexerDao).delete(Mockito.anyString(), Mockito.anyString());
    Content content = Mockito.mock(Content.class);
    when(content.getId()).thenReturn("ART124");
    PublicContentChangedEvent event = new PublicContentChangedEvent();
    event.setContent(content);
    event.setOperationCode(PublicContentChangedEvent.UPDATE_OPERATION_CODE);
    this.searchEngineManager.updateFromPublicContentChanged(event);
    Mockito.verify(indexerDao, Mockito.times(1)).delete(IIndexerDAO.CONTENT_ID_FIELD_NAME, "ART124");
    Mockito.verify(indexerDao, Mockito.times(0)).add(content);
    Mockito.verifyZeroInteractions(searcherDao);
}
 
源代码18 项目: hawkbit   文件: AmqpMessageDispatcherServiceTest.java
@Test
@Description("Verifies that a delete message is not send if the address is not an amqp address.")
public void sendDeleteRequestWithNoAmqpAdress() {

    // setup
    final String noAmqpUri = "http://anyhost";
    final TargetDeletedEvent targetDeletedEvent = new TargetDeletedEvent(TENANT, 1L, CONTROLLER_ID, noAmqpUri,
            Target.class.getName(), serviceMatcher.getServiceId());

    // test
    amqpMessageDispatcherService.targetDelete(targetDeletedEvent);

    // verify
    Mockito.verifyZeroInteractions(senderService);
}
 
源代码19 项目: entando-core   文件: ApiOAuth2TokenManagerTest.java
@Test
public void storeRefreshToken() throws Exception {
    this.tokenManager.storeRefreshToken(new DefaultOAuth2RefreshToken("value"), this.createMockAuthentication());
    Mockito.verifyZeroInteractions(tokenDAO);
}
 
源代码20 项目: bazel   文件: ByteStreamUploaderTest.java
@Test
public void singleBlobUploadShouldWork() throws Exception {
  Context prevContext = withEmptyMetadata.attach();
  RemoteRetrier retrier =
      TestUtils.newRemoteRetrier(() -> mockBackoff, (e) -> true, retryService);
  ByteStreamUploader uploader =
      new ByteStreamUploader(
          INSTANCE_NAME,
          new ReferenceCountedChannel(channel),
          null, /* timeout seconds */
          60,
          retrier);

  byte[] blob = new byte[CHUNK_SIZE * 2 + 1];
  new Random().nextBytes(blob);

  Chunker chunker = Chunker.builder().setInput(blob).setChunkSize(CHUNK_SIZE).build();
  HashCode hash = HashCode.fromString(DIGEST_UTIL.compute(blob).getHash());

  serviceRegistry.addService(new ByteStreamImplBase() {
        @Override
        public StreamObserver<WriteRequest> write(StreamObserver<WriteResponse> streamObserver) {
          return new StreamObserver<WriteRequest>() {

            byte[] receivedData = new byte[blob.length];
            long nextOffset = 0;

            @Override
            public void onNext(WriteRequest writeRequest) {
              if (nextOffset == 0) {
                assertThat(writeRequest.getResourceName()).isNotEmpty();
                assertThat(writeRequest.getResourceName()).startsWith(INSTANCE_NAME + "/uploads");
                assertThat(writeRequest.getResourceName()).endsWith(String.valueOf(blob.length));
              } else {
                assertThat(writeRequest.getResourceName()).isEmpty();
              }

              assertThat(writeRequest.getWriteOffset()).isEqualTo(nextOffset);

              ByteString data = writeRequest.getData();

              System.arraycopy(data.toByteArray(), 0, receivedData, (int) nextOffset,
                  data.size());

              nextOffset += data.size();
              boolean lastWrite = blob.length == nextOffset;
              assertThat(writeRequest.getFinishWrite()).isEqualTo(lastWrite);
            }

            @Override
            public void onError(Throwable throwable) {
              fail("onError should never be called.");
            }

            @Override
            public void onCompleted() {
              assertThat(nextOffset).isEqualTo(blob.length);
              assertThat(receivedData).isEqualTo(blob);

              WriteResponse response =
                  WriteResponse.newBuilder().setCommittedSize(nextOffset).build();
              streamObserver.onNext(response);
              streamObserver.onCompleted();
            }
          };
        }
      });

  uploader.uploadBlob(hash, chunker, true);

  // This test should not have triggered any retries.
  Mockito.verifyZeroInteractions(mockBackoff);

  blockUntilInternalStateConsistent(uploader);

  withEmptyMetadata.detach(prevContext);
}