类org.mockito.BDDMockito源码实例Demo

下面列出了怎么用org.mockito.BDDMockito的API类实例代码及写法,或者点击链接到github查看源代码。

@Test // SPR-15041
public void applicationOctetStreamDefaultContentType() throws Exception {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	ClassPathResource body = Mockito.mock(ClassPathResource.class);
	BDDMockito.given(body.getFilename()).willReturn("spring.dat");
	BDDMockito.given(body.contentLength()).willReturn(12L);
	BDDMockito.given(body.getInputStream()).willReturn(new ByteArrayInputStream("Spring Framework".getBytes()));
	HttpRange range = HttpRange.createByteRange(0, 5);
	ResourceRegion resourceRegion = range.toResourceRegion(body);

	converter.write(Collections.singletonList(resourceRegion), null, outputMessage);

	assertThat(outputMessage.getHeaders().getContentType(), is(MediaType.APPLICATION_OCTET_STREAM));
	assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE), is("bytes 0-5/12"));
	assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring"));
}
 
@Test
public void handleResponse() throws Exception {
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.given(APIUtil.isAnalyticsEnabled()).willReturn(true);
    SynapseConfiguration synCfg = new SynapseConfiguration();
    org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
    AxisConfiguration axisConfig = new AxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
    MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg,
            new Axis2SynapseEnvironment(cfgCtx, synCfg));
    synCtx.setProperty(APIMgtGatewayConstants.BACKEND_REQUEST_START_TIME, "123456789");
    APIMgtLatencyStatsHandler apiMgtLatencyStatsHandler = new APIMgtLatencyStatsHandler();
    apiMgtLatencyStatsHandler.handleResponse(synCtx);
    long backeEndLatencyTime = Long.parseLong(String.valueOf(synCtx.getProperty(APIMgtGatewayConstants
            .BACKEND_LATENCY)));
    Assert.assertTrue(backeEndLatencyTime <= System.currentTimeMillis());
    Assert.assertTrue(Long.valueOf((Long) synCtx.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME)) <=
            System.currentTimeMillis());
}
 
源代码3 项目: cloudbreak   文件: Flow2HandlerTest.java
@Test
public void testNewFlow() {
    BDDMockito.<FlowConfiguration<?>>given(flowConfigurationMap.get(any())).willReturn(flowConfig);
    given(flowConfig.createFlow(anyString(), anyLong())).willReturn(flow);
    given(flowConfig.getFlowTriggerCondition()).willReturn(flowTriggerCondition);
    given(flowTriggerCondition.isFlowTriggerable(anyLong())).willReturn(true);
    given(flow.getCurrentState()).willReturn(flowState);
    Event<Payload> event = new Event<>(payload);
    event.setKey("KEY");
    underTest.accept(event);
    verify(flowConfigurationMap, times(1)).get(anyString());
    verify(runningFlows, times(1)).put(eq(flow), isNull(String.class));
    verify(flowLogService, times(1))
            .save(any(FlowParameters.class), nullable(String.class), eq("KEY"), any(Payload.class), any(), eq(flowConfig.getClass()), eq(flowState));
    verify(flow, times(1)).sendEvent(anyString(), isNull(), any(), any());
}
 
@Before
public void setup() throws Exception {
    underTest = new TestFlowConfiguration();
    MockitoAnnotations.initMocks(this);
    BDDMockito.given(applicationContext.getBean(ArgumentMatchers.anyString(), ArgumentMatchers.any(Class.class))).willReturn(action);
    BDDMockito.given(applicationContext.getBean(ArgumentMatchers.eq(FlowEventListener.class), ArgumentMatchers.eq(State.INIT),
            ArgumentMatchers.eq(State.FINAL), ArgumentMatchers.anyString(), ArgumentMatchers.eq("flowId"),
            ArgumentMatchers.anyLong())).willReturn(flowEventListener);
    transitions = new Builder<State, Event>()
            .defaultFailureEvent(Event.FAILURE)
            .from(State.INIT).to(State.DO).event(Event.START).noFailureEvent()
            .from(State.DO).to(State.DO2).event(Event.CONTINUE).defaultFailureEvent()
            .from(State.DO2).to(State.FINISH).event(Event.FINISHED).failureState(State.FAILED2).failureEvent(Event.FAILURE2)
            .from(State.FINISH).to(State.FINAL).event(Event.FINALIZED).defaultFailureEvent()
            .build();
    edgeConfig = new FlowEdgeConfig<>(State.INIT, State.FINAL, State.FAILED, Event.FAIL_HANDLED);
    ((AbstractFlowConfiguration<State, Event>) underTest).init();
    Mockito.verify(applicationContext, Mockito.times(8)).getBean(ArgumentMatchers.anyString(), ArgumentMatchers.any(Class.class));
    flow = underTest.createFlow("flowId", 0L);
    flow.initialize(Map.of());
}
 
@Test
public void testConvertStageExceptionToError() throws StageException {
  initPulsarMessageConverterImplMock();

  Mockito.when(contextMock.getOnErrorRecord()).thenReturn(OnRecordError.TO_ERROR);

  PowerMockito.mockStatic(ServicesUtil.class);
  BDDMockito.given(ServicesUtil.parseAll(Mockito.any(), Mockito.any(),
      Mockito.anyBoolean(), Mockito.any(), Mockito.any())).willThrow(new StageException(ServiceErrors
      .SERVICE_ERROR_001, TestUtilsPulsar.getPulsarMessage().getMessageId().toString(), "convert stage exception " +
      "discard", new Exception("convert stage exception discard")));

  int count = pulsarMessageConverterImplMock.convert(Mockito.mock(BatchMaker.class),
      contextMock,
      TestUtilsPulsar.getPulsarMessage().getMessageId().toString(),
      TestUtilsPulsar.getPulsarMessage()
  );

  Assert.assertEquals(0, count);
}
 
@Test
public void standardApplicationContext() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(getClass());
	given(testContext.getApplicationContext()).willReturn(mock(ApplicationContext.class));

	listener.beforeTestClass(testContext);
	assertAttributeExists();

	listener.prepareTestInstance(testContext);
	assertAttributeExists();

	listener.beforeTestMethod(testContext);
	assertAttributeExists();

	listener.afterTestMethod(testContext);
	assertAttributeExists();
}
 
@Test
public void should_update_sagan_from_release_version() {
	ProjectVersion projectVersion = version("1.0.0.RELEASE");

	this.saganUpdater.updateSagan(new File("."), "master", projectVersion,
			projectVersion, projects);

	then(this.saganClient).should().deleteRelease("foo", "1.0.0.RC1");
	then(this.saganClient).should().deleteRelease("foo", "1.0.0.BUILD-SNAPSHOT");
	then(this.saganClient).should().updateRelease(BDDMockito.eq("foo"),
			BDDMockito.argThat(withReleaseUpdate("1.0.0.RELEASE",
					"https://cloud.spring.io/spring-cloud-static/foo/{version}/",
					"GENERAL_AVAILABILITY")));
	then(this.saganClient).should().deleteRelease("foo", "1.0.0.BUILD-SNAPSHOT");
	then(this.saganClient).should().updateRelease(BDDMockito.eq("foo"),
			BDDMockito.argThat(withReleaseUpdate("1.0.1.BUILD-SNAPSHOT",
					"https://cloud.spring.io/foo/foo.html", "SNAPSHOT")));
}
 
源代码8 项目: shib-cas-authn3   文件: ShibcasAuthServletTest.java
private ServletConfig createMockServletConfig(final String entityIdLocation) {
    final ServletConfig config = Mockito.mock(ServletConfig.class);
    final ServletContext servletContext = Mockito.mock(ServletContext.class);
    final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
    final Environment environment = Mockito.mock(Environment.class);
    
    BDDMockito.given(config.getServletContext()).willReturn(servletContext);
    BDDMockito.given(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).willReturn(applicationContext);
    BDDMockito.given(applicationContext.getEnvironment()).willReturn(environment);
    BDDMockito.given(environment.getRequiredProperty("shibcas.casServerUrlPrefix")).willReturn("https://cassserver.example.edu/cas");
    BDDMockito.given(environment.getRequiredProperty("shibcas.casServerLoginUrl")).willReturn("https://cassserver.example.edu/cas/login");
    BDDMockito.given(environment.getRequiredProperty("shibcas.serverName")).willReturn("https://shibserver.example.edu");
    BDDMockito.given(environment.getRequiredProperty("shibcas.casToShibTranslators")).willReturn(null);
    BDDMockito.given(environment.getProperty("shibcas.ticketValidatorName", "cas30")).willReturn("cas30");

    if (StringUtils.isNotEmpty(entityIdLocation)) {
        BDDMockito.given(environment.getProperty("shibcas.entityIdLocation", "append")).willReturn(entityIdLocation);
    } else {
        BDDMockito.given(environment.getProperty("shibcas.entityIdLocation", "append")).willReturn("append");
    }

    return config;
}
 
@Test
public void should_not_finalize_the_delegate_since_its_a_shared_instance() {
	AtomicBoolean wasCalled = new AtomicBoolean();
	ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10) {
		@Override
		protected void finalize() {
			super.finalize();
			wasCalled.set(true);
		}
	};
	BeanFactory beanFactory = BDDMockito.mock(BeanFactory.class);

	new LazyTraceScheduledThreadPoolExecutor(10, beanFactory, executor).finalize();

	BDDAssertions.then(wasCalled).isFalse();
	BDDAssertions.then(executor.isShutdown()).isFalse();
}
 
@Test
public void should_update_docs_for_sagan_when_current_version_newer_and_only_overview_adoc_exists()
		throws IOException {
	given(this.saganClient.updateRelease(BDDMockito.anyString(),
			BDDMockito.anyList())).willReturn(a2_0_0_ReleaseProject());

	Path tmp = Files.createTempDirectory("releaser-test");
	createFile(tmp, "sagan-index.adoc", "new text");
	SaganUpdater saganUpdater = new SaganUpdater(this.saganClient, this.properties) {
		@Override
		File docsModule(File projectFile) {
			return tmp.toFile();
		}
	};

	saganUpdater.updateSagan(new File("."), "master", version("3.0.0.RC1"),
			version("3.0.0.RC1"), projects);

	then(this.saganClient).should().patchProject(
			BDDMockito.argThat(argument -> "new text".equals(argument.rawOverview)));
}
 
源代码11 项目: PermissMe   文件: PermissMeUtilsTest.java
@Test
public void testGetDeniedPermissions_whenAllPermissionsUngranted_returnAllPermissions() {
	// Case 4: 2 permissions, 2 ungranted
	BDDMockito.given(
			PermissionChecker.checkSelfPermission(any(Context.class), anyString())
	).willReturn(PackageManager.PERMISSION_DENIED);

	String[] deniedPermissions = PermissMeUtils.getDeniedPermissions(
			mockContext,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_SMS
	);
	assertNotNull(deniedPermissions);
	assertTrue(deniedPermissions.length == 2);
	assertTrue(deniedPermissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE));
	assertTrue(deniedPermissions[1].equals(Manifest.permission.READ_SMS));
}
 
源代码12 项目: shib-cas-authn3   文件: ShibcasAuthServletTest.java
@Test
public void testDoGetBadTicket() throws Exception {
    //Mock some objects.
    final HttpServletRequest request = createDoGetHttpServletRequest(CONVERSATION_TICKET, TICKET, "false");
    final HttpServletResponse response = createMockHttpServletResponse();
    final Cas20ServiceTicketValidator ticketValidator = PowerMockito.mock(Cas20ServiceTicketValidator.class);
    PowerMockito.when(ticketValidator.validate(TICKET, URL_WITH_CONVERSATION)).thenThrow(new TicketValidationException("Invalid Ticket"));

    PowerMockito.mockStatic(ExternalAuthentication.class);
    BDDMockito.given(ExternalAuthentication.startExternalAuthentication(request)).willThrow(new ExternalAuthenticationException());

    //Prep our object
    final ShibcasAuthServlet shibcasAuthServlet = createShibcasAuthServlet();

    //Override the internal Cas20TicketValidator because we don't want it to call a real server
    MemberModifier.field(ShibcasAuthServlet.class, "ticketValidator").set(shibcasAuthServlet, ticketValidator);

    //Standard request/response - bad ticket
    BDDMockito.given(request.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM)).willReturn("false");
    BDDMockito.given(request.getAttribute(ExternalAuthentication.PASSIVE_AUTHN_PARAM)).willReturn("false");
    shibcasAuthServlet.doGet(request, response);

    //Verify
    verify(request).getRequestDispatcher("/no-conversation-state.jsp");
    verify(response).setStatus(404);
}
 
@Test
public void missingValueAndScriptsAndStatementsAtClassLevel() throws Exception {
	Class<?> clazz = MissingValueAndScriptsAndStatementsAtClassLevel.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));

	assertExceptionContains(clazz.getSimpleName() + ".sql");
}
 
@Test
public void setThreadFactory() {
	ThreadFactory threadFactory = r -> null;
	this.executor.setThreadFactory(threadFactory);

	BDDMockito.then(this.delegate).should().setThreadFactory(threadFactory);
}
 
@Test
public void should_do_nothing_when_bean_is_already_traceable_executor()
		throws Exception {
	TraceableExecutorService service = BDDMockito
			.mock(TraceableExecutorService.class);

	Object o = new ExecutorBeanPostProcessor(this.beanFactory)
			.postProcessAfterInitialization(service, "foo");

	then(o).isSameAs(service);
}
 
@Test
public void atWebAppConfigTestCaseWithoutExistingRequestAttributes() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(AtWebAppConfigWebTestCase.class);

	RequestContextHolder.resetRequestAttributes();
	listener.beforeTestClass(testContext);
	assertRequestAttributesDoNotExist();

	assertWebAppConfigTestCase();
}
 
@Test
public void missingValueAndScriptsAndStatementsAtMethodLevel() throws Exception {
	Class<?> clazz = MissingValueAndScriptsAndStatementsAtMethodLevel.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));

	assertExceptionContains(clazz.getSimpleName() + ".foo" + ".sql");
}
 
源代码18 项目: cyclops   文件: SyncIOTest.java
@Test
public void shouldSucceedAfterFewAsynchronousRetries() throws Exception {


    BDDMockito.given(serviceMock.apply(Matchers.anyInt())).willThrow(
        new RuntimeException(new SocketException("First")),
        new RuntimeException(new IOException("Second"))).willReturn(
        "42");

    String result = IO.sync( ReactiveSeq.of(1,  2, 3))
        .retry(serviceMock)
        .run().mkString();

    Assert.assertThat(result, is("Success[42]"));
}
 
@Test
public void beforeAndAfterTestMethodForDirtiesContextViaMetaAnnotationWithOverrides() throws Exception {
	Class<?> clazz = DirtiesContextViaMetaAnnotationWithOverrides.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("clean"));
	beforeListener.beforeTestMethod(testContext);
	afterListener.beforeTestMethod(testContext);
	verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class));
	afterListener.afterTestMethod(testContext);
	beforeListener.afterTestMethod(testContext);
	verify(testContext, times(1)).markApplicationContextDirty(CURRENT_LEVEL);
}
 
源代码20 项目: cyclops   文件: BatchingCollectorTest.java
@Test
public void testBatchingCollectorMaxActive() {
	collector = new BatchingCollector(new MaxActive(10,5), LazyReact.sequentialBuilder().of(1)).withResults(new HashSet<>());
	FastFuture cf = Mockito.mock(FastFuture.class);
	BDDMockito.given(cf.isDone()).willReturn(true);
	for(int i=0;i<1000;i++){
		collector.accept(cf);
	}
	Mockito.verify(cf, Mockito.times(990)).isDone();
}
 
@Test
public void setThreadGroup() {
	ThreadGroup threadGroup = new ThreadGroup("foo");
	this.executor.setThreadGroup(threadGroup);

	BDDMockito.then(this.delegate).should().setThreadGroup(threadGroup);
}
 
@Test
public void should_build_and_deploy_guides_when_switch_is_on() throws Exception {
	this.properties.getGit().setUpdateSpringGuides(true);
	String projects = this.temporaryFolder.getAbsolutePath();
	this.properties.getMetaRelease().setGitOrgUrl(projects);
	VersionsFetcher versionsFetcher = BDDMockito.mock(VersionsFetcher.class);
	BDDMockito.given(versionsFetcher.isLatestGa(BDDMockito.any())).willReturn(true);
	AtomicReference<ProjectCommandExecutor> projectBuilderStub = new AtomicReference<>();
	ProjectGitHandler handler = BDDMockito.mock(ProjectGitHandler.class);
	ProjectCommandExecutor projectCommandExecutor = BDDMockito
			.mock(ProjectCommandExecutor.class);
	PostReleaseActions actions = new PostReleaseActions(handler, this.updater,
			this.gradleUpdater, this.commandExecutor, this.properties,
			versionsFetcher, releaserPropertiesUpdater) {
		@Override
		ProjectCommandExecutor projectBuilder(ProcessedProject processedProject) {
			projectBuilderStub.set(projectCommandExecutor);
			return projectCommandExecutor;
		}
	};
	ProjectVersion projectVersion = new ProjectVersion(
			new File(projects, "spring-cloud-release"));

	actions.deployGuides(Collections.singletonList(
			new ProcessedProject(this.properties, projectVersion, projectVersion)));

	Awaitility.await().untilAsserted(() -> {
		BDDAssertions.then(projectBuilderStub.get()).isNotNull();
		BDDMockito.then(projectBuilderStub.get()).should()
				.deployGuides(this.properties, projectVersion, projectVersion);
	});
}
 
源代码23 项目: openmeetings   文件: TestRecordingFlowMocked.java
@Override
public void setup() {
	super.setup();
	doReturn(mock(MediaPipeline.class)).when(client).createMediaPipeline(any(Transaction.class));
	User u = new User();
	u.setId(USER_ID);
	u.setFirstname("firstname");
	u.setLastname("lastname");
	doReturn(u).when(userDao).get(USER_ID);
	doReturn(true).when(handler).isConnected();
	when(recDao.update(any(Recording.class))).thenAnswer((invocation) ->  {
		Object[] args = invocation.getArguments();
		Recording r = (Recording) args[0];
		r.setId(1L);
		return r;
	});

	PowerMockito.mockStatic(LabelDao.class);
	BDDMockito.given(LabelDao.getLanguage(any(Long.class))).willReturn(new OmLanguage(Locale.ENGLISH));

	// init client object for this test
	c = getClientFull();
	doReturn(c.getRoom()).when(roomDao).get(ROOM_ID);

	// Mock out the methods that do webRTC
	doReturn(null).when(streamProcessor).startBroadcast(any(), any(), any());

}
 
@Test
public void should_update_sagan_from_master() {
	ProjectVersion projectVersion = version("1.0.0.BUILD-SNAPSHOT");

	this.saganUpdater.updateSagan(new File("."), "master", projectVersion,
			projectVersion, projects);

	then(this.saganClient).should().updateRelease(BDDMockito.eq("foo"),
			BDDMockito.argThat(withReleaseUpdate("1.0.0.BUILD-SNAPSHOT",
					"https://cloud.spring.io/foo/foo.html", "SNAPSHOT")));
}
 
@Test
public void should_do_nothing_when_guides_are_turned_off() {
	this.properties.getGit().setUpdateSpringGuides(false);
	VersionsFetcher versionsFetcher = BDDMockito.mock(VersionsFetcher.class);
	PostReleaseActions actions = new PostReleaseActions(this.projectGitHandler,
			this.updater, this.gradleUpdater, this.commandExecutor, this.properties,
			versionsFetcher, releaserPropertiesUpdater);

	actions.deployGuides(Collections.emptyList());

	BDDAssertions.then(this.cloned).isNull();
	BDDMockito.then(versionsFetcher).shouldHaveZeroInteractions();
}
 
源代码26 项目: PermissMe   文件: PermissMeUtilsTest.java
@Test
public void testPermissionIsInvalidOrHasPermission_whenPermissionValidAndUngranted_returnFalse() {
	final String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
	// Case 3: Ungranted permission
	BDDMockito.given(
			PermissionChecker.checkSelfPermission(any(Context.class), eq(permission))
	).willReturn(PackageManager.PERMISSION_DENIED);
	final boolean result = PermissMeUtils.permissionIsInvalidOrHasPermission(mockContext, permission);
	assertFalse(result);
}
 
@Test
public void keep_requestTemplate() throws IOException {
	BDDMockito.given(this.client.execute(BDDMockito.any(), BDDMockito.any()))
			.willAnswer(new Answer() {
				public Object answer(InvocationOnMock invocation) {
					Object[] args = invocation.getArguments();
					Assert.assertEquals(((Request) args[0]).requestTemplate(),
							requestTemplate);
					return null;
				}
			});
	this.traceFeignClient.execute(this.request, this.options);
}
 
@Test
public void beforeAndAfterTestMethodForDirtiesContextDeclaredOnMethodViaMetaAnnotationWithAfterMethodMode()
		throws Exception {
	Class<?> clazz = getClass();
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	given(testContext.getTestMethod()).willReturn(
		clazz.getDeclaredMethod("dirtiesContextDeclaredViaMetaAnnotationWithAfterMethodMode"));
	beforeListener.beforeTestMethod(testContext);
	afterListener.beforeTestMethod(testContext);
	verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class));
	afterListener.afterTestMethod(testContext);
	beforeListener.afterTestMethod(testContext);
	verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE);
}
 
@Test
public void should_not_update_docs_for_sagan_when_current_version_older() {
	given(this.saganClient.updateRelease(BDDMockito.anyString(),
			BDDMockito.anyList())).willReturn(a2_0_0_ReleaseProject());

	this.saganUpdater.updateSagan(new File("."), "master", version("1.0.0.RC1"),
			version("1.0.0.RC1"), projects);

	then(this.saganClient).should(BDDMockito.never())
			.patchProject(BDDMockito.any(Project.class));

}
 
@Test
public void should_not_schedule_a_trace_callable_when_context_not_ready()
		throws Exception {
	SleuthContextListenerAccessor.set(this.beanFactory, false);
	this.traceableScheduledExecutorService.schedule(aCallable(), 1L, TimeUnit.DAYS);

	then(this.scheduledExecutorService).should(never()).schedule(
			BDDMockito.argThat(
					matcher(Callable.class, instanceOf(TraceCallable.class))),
			anyLong(), any(TimeUnit.class));
}
 
 类所在包
 同包方法