org.mockito.BDDMockito Java Examples

The following examples show how to use org.mockito.BDDMockito. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestPulsarMessageConverterImpl.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: PermissMeUtilsTest.java    From PermissMe with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #3
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: ResourceRegionHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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"));
}
 
Example #5
Source File: APIMgtLatencyStatsHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: Flow2HandlerTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #7
Source File: SaganUpdaterOldDocsTest.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #8
Source File: AbstractFlowConfigurationTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source File: LazyTraceScheduledThreadPoolExecutorTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #10
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: SaganUpdaterOldDocsTest.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
@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")));
}
 
Example #12
Source File: ServletTestExecutionListenerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #13
Source File: MapCloudhopperCharsetHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test(expected = EncodingException.class)
public void encodeWithUnmappedCloudhopperCharset() throws EncodingException {
	// given
	String givenContent = "méss@ge àvec des acçènts & d€$ cara©tères spécïaùx";
	String givenNioCharsetName = "charset";

	Charset nioCharsetMock = new Charset(givenNioCharsetName, null) {
		@Override
		public CharsetEncoder newEncoder() {
			return null;
		}

		@Override
		public CharsetDecoder newDecoder() {
			return null;
		}

		@Override
		public boolean contains(Charset cs) {
			return false;
		}
	};

	BDDMockito.given(charsetProviderMock.detect(givenContent)).willReturn(nioCharsetMock);

	// when
	charsetHandler.encode(givenContent);
}
 
Example #14
Source File: DirtiesContextTestExecutionListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void beforeAndAfterTestClassForDirtiesContextDeclaredLocallyOnClassBeforeEachTestMethod() throws Exception {
	Class<?> clazz = DirtiesContextDeclaredLocallyBeforeEachTestMethod.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	beforeListener.beforeTestClass(testContext);
	afterListener.beforeTestClass(testContext);
	afterListener.afterTestClass(testContext);
	beforeListener.afterTestClass(testContext);
	verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class));
}
 
Example #15
Source File: BlockingConditionRetrieverTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws Exception {

    String content = "{\"api\":[\"/pizzashack/1.0.0\"],\"application\":[\"admin:DefaultApplication\"]," +
            "\"ip\":[{\"fixedIp\":\"127.0.0.1\",\"invert\":false,\"type\":\"IP\",\"tenantDomain\":\"carbon" +
            ".super\"}],\"user\":[\"admin\"],\"custom\":[]}";
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(content.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    BDDMockito.given(APIUtil.getHttpClient(Mockito.anyInt(), Mockito.anyString())).willReturn(httpClient);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setUsername("admin");
    eventHubConfigurationDto.setPassword("admin".toCharArray());
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setServiceUrl("http://localhost:18083/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    BlockingConditionRetriever blockingConditionRetriever =
            new BlockingConditionRetrieverWrapper(eventHubConfigurationDto, throttleDataHolder);
    blockingConditionRetriever.run();
    Assert.assertTrue(throttleDataHolder.isRequestBlocked("/pizzashack/1.0.0", "admin:DefaultApplication",
            "admin", "127.0.0.1", "carbon.super",
            "/pizzashack/1.0.0:1.0.0:admin-DefaultApplication"));
}
 
Example #16
Source File: DirtiesContextTestExecutionListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void beforeAndAfterTestMethodForDirtiesContextDeclaredLocallyOnClassAfterEachTestMethod() throws Exception {
	Class<?> clazz = DirtiesContextDeclaredLocallyAfterEachTestMethod.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(EXHAUSTIVE);
}
 
Example #17
Source File: DirtiesContextTestExecutionListenerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void beforeAndAfterTestClassForDirtiesContextDeclaredLocallyOnClassAfterClass() throws Exception {
	Class<?> clazz = DirtiesContextDeclaredLocallyAfterClass.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	beforeListener.beforeTestClass(testContext);
	afterListener.beforeTestClass(testContext);
	verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class));
	afterListener.afterTestClass(testContext);
	beforeListener.afterTestClass(testContext);
	verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE);
}
 
Example #18
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPolicies() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException,
        RegistryException {
    APIPolicy[] policies1 = { new APIPolicy("policy1") };
    ApplicationPolicy[] policies2 = { new ApplicationPolicy("policy2"), new ApplicationPolicy("policy3") };
    SubscriptionPolicy[] policies3 = { new SubscriptionPolicy("policy4"), new SubscriptionPolicy("policy5"),
            new SubscriptionPolicy("policy6") };
    GlobalPolicy[] policies4 = { new GlobalPolicy("policy7"), new GlobalPolicy("policy8"),
            new GlobalPolicy("policy9"), new GlobalPolicy("policy0") };
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIPolicies(Mockito.anyInt())).thenReturn(policies1);
    Mockito.when(apiMgtDAO.getApplicationPolicies(Mockito.anyInt())).thenReturn(policies2);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(Mockito.anyInt())).thenReturn(policies3);
    Mockito.when(apiMgtDAO.getGlobalPolicies(Mockito.anyInt())).thenReturn(policies4);

    ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class, Mockito.RETURNS_MOCKS);

    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);

    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_API).length, 1);
    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_APP).length, 2);

    PowerMockito.when(throttleProperties.isEnableUnlimitedTier()).thenReturn(false);

    Assert.assertEquals(3, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_SUB).length);
    Assert.assertEquals(4, abstractAPIManager.getPolicies(API_PROVIDER,
            PolicyConstants.POLICY_LEVEL_GLOBAL).length);
    Assert.assertEquals(0, abstractAPIManager.getPolicies(API_PROVIDER, "Test").length);
}
 
Example #19
Source File: LazyTraceThreadPoolTaskSchedulerTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void schedule2() {
	Runnable r = () -> {
	};
	Instant instant = Instant.now();
	this.executor.schedule(r, instant);

	BDDMockito.then(this.delegate).should()
			.schedule(BDDMockito.any(TraceRunnable.class), BDDMockito.eq(instant));
}
 
Example #20
Source File: DirtiesContextTestExecutionListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #21
Source File: TransactionalTestExecutionListenerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void assertAfterTestMethodWithTransactionalTestMethod(Class<? extends Invocable> clazz) throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	Invocable instance = clazz.newInstance();
	given(testContext.getTestInstance()).willReturn(instance);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest"));

	given(tm.getTransaction(BDDMockito.any(TransactionDefinition.class))).willReturn(new SimpleTransactionStatus());

	assertFalse(instance.invoked);
	TransactionContextHolder.removeCurrentTransactionContext();
	listener.beforeTestMethod(testContext);
	listener.afterTestMethod(testContext);
	assertTrue(instance.invoked);
}
 
Example #22
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
private HttpServletResponse createMockHttpServletResponse() {
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    BDDMockito.given(response.encodeURL(URL_WITH_CONVERSATION)).willReturn(URL_WITH_CONVERSATION);
    BDDMockito.given(response.encodeURL(URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED)).willReturn(URL_WITH_CONVERSATION_GATEWAY_ATTEMPTED);
    BDDMockito.given(response.encodeURL(URL_WITH_CONVERSATION_EMBEDDED_ENTITYID)).willReturn(URL_WITH_CONVERSATION_EMBEDDED_ENTITYID);

    return response;
}
 
Example #23
Source File: ServletTestExecutionListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * @since 4.3
 */
@Test
public void activateListenerWithoutExistingRequestAttributes() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(NoAtWebAppConfigWebTestCase.class);
	given(testContext.getAttribute(ServletTestExecutionListener.ACTIVATE_LISTENER)).willReturn(true);

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

	assertWebAppConfigTestCase();
}
 
Example #24
Source File: ServletTestExecutionListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void atWebAppConfigTestCaseWithPresetRequestAttributes() throws Exception {
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(AtWebAppConfigWebTestCase.class);

	listener.beforeTestClass(testContext);
	assertRequestAttributesExist();

	assertWebAppConfigTestCase();
}
 
Example #25
Source File: DirtiesContextTestExecutionListenerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void beforeAndAfterTestMethodForDirtiesContextDeclaredViaMetaAnnotationOnClassAfterEachTestMethod()
		throws Exception {
	Class<?> clazz = DirtiesContextDeclaredViaMetaAnnotationAfterEachTestMethod.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(EXHAUSTIVE);
}
 
Example #26
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartLoginRequestPassiveAndForced() throws Exception {
    final HttpServletRequest request = createMockHttpServletRequest();
    BDDMockito.given(request.getQueryString()).willReturn(CONVERSATION);

    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    BDDMockito.given(response.encodeURL(URL_WITH_CONVERSATION)).willReturn(URL_WITH_CONVERSATION);

    final ShibcasAuthServlet shibcasAuthServlet = new ShibcasAuthServlet();
    shibcasAuthServlet.init(createMockServletConfig());

    //Passive and Forced
    shibcasAuthServlet.startLoginRequest(request, response, true, true, "");
    verify(response).sendRedirect("https://cassserver.example.edu/cas/login?service=https%3A%2F%2Fshibserver.example.edu%2Fidp%2FAuthn%2FExtCas%3Fconversation%3De1s1%26gatewayAttempted%3Dtrue&renew=true&gateway=true&entityId=http%3A%2F%2Ftest.edu%2Fsp");
}
 
Example #27
Source File: ClusterStatusUpdaterTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateClusterStatusShouldUpdateWhenStackStatusStopped() {
    // GIVEN
    Stack stack = createStack(Status.STOPPED, Status.AVAILABLE);
    // WHEN
    underTest.updateClusterStatus(stack, stack.getCluster());
    // THEN
    BDDMockito.verify(clusterService, BDDMockito.times(1)).updateClusterStatusByStackId(any(Long.class), eq(stack.getStatus()));
}
 
Example #28
Source File: ExecutorBeanPostProcessorTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_do_nothing_when_bean_is_already_lazy_trace_async_task_executor()
		throws Exception {
	LazyTraceAsyncTaskExecutor service = BDDMockito
			.mock(LazyTraceAsyncTaskExecutor.class);

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

	then(o).isSameAs(service);
}
 
Example #29
Source File: BencodeTest.java    From algorithms with MIT License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIllegalStateExceptionCharacter() throws IOException {
    InputStream inputStream = BDDMockito.mock(InputStream.class);

    BDDMockito.given(inputStream.read()).willThrow(new IOException());

    new CharacterInputStreamIterator(inputStream).hasNext();
}
 
Example #30
Source File: ServiceResponseDecoderTest.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaders() throws Exception {
    HttpResponse mockHttpResponse = mock(HttpResponse.class);
    StatusLine mockStatusLine = mock(StatusLine.class);
    HttpEntity mockEntity = mock(HttpEntity.class);
    InputStream stream = mock(InputStream.class);
    mockStatic(IOUtils.class);

    Header headerOne = new BasicHeader("one", "1");
    Header headerTwo = new BasicHeader("two", "2");
    Header[] responseHeaders = new Header[] { headerOne, headerTwo };

    when(mockStatusLine.getStatusCode()).thenReturn(200);
    when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);
    when(mockHttpResponse.getEntity()).thenReturn(mockEntity);
    when(mockHttpResponse.getAllHeaders()).thenReturn(responseHeaders);
    when(mockEntity.getContent()).thenReturn(stream);
    BDDMockito.when(IOUtils.toString(stream)).thenReturn("success");
    when(mockJavaType.getRawClass()).thenReturn(responseClass);

    ServiceResponseDecoder decoder = spy(new ServiceResponseDecoder(mockMapper, mockJavaType, mockErrorType, mockLogger , exceptions, collectedHeaders));
    ServiceResponse response = decoder.decode(mockHttpResponse);
    assertEquals("success", response.getDataList().get(0));
    assertEquals(2, response.getHeaders().size());
    assertEquals("1", response.getHeaders().get("one"));
    assertEquals("2", response.getHeaders().get("two"));
    assertEquals(0, collectedHeaders.size());
    Mockito.verify(mockLogger, Mockito.never());
}