Java Code Examples for org.mockito.internal.util.reflection.Whitebox

The following examples show how to use org.mockito.internal.util.reflection.Whitebox. These examples are extracted from open source projects. 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 Project: big-c   Source File: TestDeleteRace.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  try {
    Thread.sleep(1000);
    LOG.info("Deleting" + path);
    final FSDirectory fsdir = cluster.getNamesystem().dir;
    INode fileINode = fsdir.getINode4Write(path.toString());
    INodeMap inodeMap = (INodeMap) Whitebox.getInternalState(fsdir,
        "inodeMap");

    fs.delete(path, false);
    // after deletion, add the inode back to the inodeMap
    inodeMap.put(fileINode);
    LOG.info("Deleted" + path);
  } catch (Exception e) {
    LOG.info(e);
  }
}
 
Example 2
@Before
public void setup() throws IOException {
    searchFilterServiceUnderTest = context.registerInjectActivateService(new SearchFilterServiceImpl());

    graphqlClient = new GraphqlClientImpl();
    Whitebox.setInternalState(graphqlClient, "gson", QueryDeserializer.getGson());
    Whitebox.setInternalState(graphqlClient, "client", httpClient);
    Whitebox.setInternalState(graphqlClient, "httpMethod", HttpMethod.POST);

    Utils.setupHttpResponse("graphql/magento-graphql-introspection-result.json", httpClient, HttpStatus.SC_OK, "{__type");
    Utils.setupHttpResponse("graphql/magento-graphql-attributes-result.json", httpClient, HttpStatus.SC_OK, "{customAttributeMetadata");

    page = Mockito.spy(context.currentPage(PAGE));
    pageResource = Mockito.spy(page.adaptTo(Resource.class));
    when(page.adaptTo(Resource.class)).thenReturn(pageResource);
}
 
Example 3
@Test
public void testCategoryNotOrNoChildren() throws IOException {
    Page page = mock(Page.class);
    Resource pageContent = mock(Resource.class);
    when(page.getContentResource()).thenReturn(pageContent);
    GraphQLCategoryProvider categoryProvider = new GraphQLCategoryProvider(page
        .getContentResource(), null);
    MagentoGraphqlClient graphqlClient = mock(MagentoGraphqlClient.class);
    Whitebox.setInternalState(categoryProvider, "magentoGraphqlClient", graphqlClient);

    // test category not found
    GraphqlResponse<Query, Error> response = mock(GraphqlResponse.class);
    when(graphqlClient.execute(anyString())).thenReturn(response);
    Query rootQuery = mock(Query.class);
    when(response.getData()).thenReturn(rootQuery);
    Assert.assertNull(rootQuery.getCategory());
    Assert.assertTrue(categoryProvider.getChildCategories(-10, 10).isEmpty());

    // test category children not found
    CategoryTree category = mock(CategoryTree.class);
    when(rootQuery.getCategory()).thenReturn(category);
    when(category.getChildren()).thenReturn(null);
    Assert.assertNull(category.getChildren());
    Assert.assertTrue(categoryProvider.getChildCategories(13, 10).isEmpty());
}
 
Example 4
@Test
public void testQueryExtensions() throws Exception {
    setUp(RelationType.RELATED_PRODUCTS, "graphql/magento-graphql-relatedproducts-result.json", false);
    AbstractProductsRetriever retriever = relatedProducts.getProductsRetriever();
    retriever.extendProductQueryWith(p -> p.description(d -> d.html()));
    retriever.extendVariantQueryWith(v -> v.sku());

    MagentoGraphqlClient client = (MagentoGraphqlClient) Whitebox.getInternalState(retriever, "client");
    MagentoGraphqlClient clientSpy = Mockito.spy(client);
    Whitebox.setInternalState(retriever, "client", clientSpy);

    assertProducts();

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(clientSpy, times(1)).execute(captor.capture());

    String expectedQuery = "{products(filter:{sku:{eq:\"24-MG01\"}}){items{__typename,related_products{__typename,sku,name,thumbnail{label,url},url_key,price_range{minimum_price{regular_price{value,currency},final_price{value,currency},discount{amount_off,percent_off}}},... on ConfigurableProduct{price_range{maximum_price{regular_price{value,currency},final_price{value,currency},discount{amount_off,percent_off}}}},... on ConfigurableProduct{variants{product{sku}}},description{html}}}}}";
    Assert.assertEquals(expectedQuery, captor.getValue());
}
 
Example 5
Source Project: marathon-plugin   Source File: DcosAuthImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that all other algorithms besides RS256 are rejected.
 *
 * @throws Exception
 */
@Test
public void testHSSecretKey() throws Exception {
    final Secret   secret = PowerMockito.mock(Secret.class);
    final String[] algs   = new String[]{"HS512", "HS256", "RS512"};
    for (final String alg : algs) {
        final String secretText = String.format(DCOS_AUTH_JSON, testUser, "a secret key", alg);

        Whitebox.setInternalState(secret, "value", secretText);

        when(credentials.getSecret()).thenReturn(secret);
        when(secret.getPlainText()).thenReturn(secretText);

        final DcosAuthImpl dcosAuth = new DcosAuthImpl(credentials,
                options,
                ContentType.APPLICATION_JSON,
                builder,
                context);
        try {
            dcosAuth.createDcosLoginPayload();
            assertFalse("Invalid algorithm was accepted", true);
        } catch (AuthenticationException e) {
            assertTrue("Does not list valid algorithm in message", e.getMessage().contains("RS256"));
        }
    }
}
 
Example 6
Source Project: incubator-ratis   Source File: TestRaftStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMetaFile() throws Exception {
  RaftStorage storage = new RaftStorage(storageDir, StartupOption.FORMAT);
  File m = storage.getStorageDir().getMetaFile();
  Assert.assertTrue(m.exists());
  MetaFile metaFile = new MetaFile(m);
  Assert.assertEquals(MetaFile.DEFAULT_TERM, metaFile.getTerm());
  Assert.assertEquals(MetaFile.EMPTY_VOTEFOR, metaFile.getVotedFor());

  metaFile.set(123, "peer1");
  metaFile.readFile();
  Assert.assertEquals(123, metaFile.getTerm());
  Assert.assertEquals("peer1", metaFile.getVotedFor());

  MetaFile metaFile2 = new MetaFile(m);
  Assert.assertFalse((Boolean) Whitebox.getInternalState(metaFile2, "loaded"));
  Assert.assertEquals(123, metaFile.getTerm());
  Assert.assertEquals("peer1", metaFile.getVotedFor());

  storage.close();
}
 
Example 7
@Test
public void constructor_sets_fields_as_expected() {
    // when
    SpringWebfluxUnhandledExceptionHandler handler = new SpringWebfluxUnhandledExceptionHandler(
        testProjectApiErrors, generalUtils, springUtilsMock, viewResolversProviderMock,
        serverCodecConfigurerMock
    );

    // then
    assertThat(Whitebox.getInternalState(handler, "projectApiErrors")).isSameAs(testProjectApiErrors);
    assertThat(Whitebox.getInternalState(handler, "utils")).isSameAs(generalUtils);
    assertThat(handler.springUtils).isEqualTo(springUtilsMock);
    assertThat(handler.messageReaders).isEqualTo(messageReaders);
    assertThat(handler.messageWriters).isEqualTo(messageWriters);
    assertThat(handler.viewResolvers).isEqualTo(viewResolvers);
    assertThat(handler.singletonGenericServiceError)
        .isEqualTo(Collections.singleton(testProjectApiErrors.getGenericServiceError()));
    assertThat(handler.genericServiceErrorHttpStatusCode)
        .isEqualTo(testProjectApiErrors.getGenericServiceError().getHttpStatusCode());
}
 
Example 8
@Before
public void beforeMethod() {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getRequestURI()).thenReturn("/fake/path");
    when(mockRequest.getMethod()).thenReturn("GET");
    when(mockRequest.getQueryString()).thenReturn("queryString");

    listenerList = new Jersey2ApiExceptionHandlerListenerList(
        Jersey2BackstopperConfigHelper.defaultApiExceptionHandlerListeners(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL));

    unhandledSpy = spy(new JaxRsUnhandledExceptionHandler(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL));

    handlerSpy = spy(new Jersey2ApiExceptionHandler(
        testProjectApiErrors,
        listenerList,
        ApiExceptionHandlerUtils.DEFAULT_IMPL, unhandledSpy));
    Whitebox.setInternalState(handlerSpy, "request", mockRequest);
    Whitebox.setInternalState(handlerSpy, "response", mock(HttpServletResponse.class));
}
 
Example 9
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void builder_withTags_does_nothing_if_passed_null() {
    // given
    Span.Builder builder = Span.newBuilder("foo", SpanPurpose.UNKNOWN);
    Map<String, String> tagsMapSpy = spy(new LinkedHashMap<>());
    Whitebox.setInternalState(builder, "tags", tagsMapSpy);
    
    // when
    Span.Builder resultingBuilder = builder.withTags(null);

    // then
    assertThat(resultingBuilder).isSameAs(builder);
    verifyZeroInteractions(tagsMapSpy);

    // and when
    Span resultingSpan = resultingBuilder.build();

    // then
    assertThat(resultingSpan.getTags()).isEmpty();
}
 
Example 10
@Test
public void testUpdateNotReadyToReady() throws Exception {
    // conditions
    Whitebox.setInternalState(governor, "bluetoothObject", null);
    governor.addGovernorListener(governorListener);

    governor.update();

    InOrder inOrder = inOrder(governor, governorListener, bluetoothManager);
    inOrder.verify(bluetoothManager).getBluetoothObject(URL);
    inOrder.verify(governor).init(bluetoothObject);
    inOrder.verify(governorListener).ready(true);
    inOrder.verify(governorListener, never()).lastUpdatedChanged(any());

    governor.updateLastInteracted();
    governor.update();
    inOrder.verify(governorListener).lastUpdatedChanged(any());

    inOrder.verifyNoMoreInteractions();
}
 
Example 11
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void builder_withTimestampedAnnotations_does_nothing_if_passed_null() {
    // given
    Span.Builder builder = Span.newBuilder("foo", SpanPurpose.UNKNOWN);
    List<TimestampedAnnotation> annotationsListSpy = spy(new ArrayList<>());
    Whitebox.setInternalState(builder, "annotations", annotationsListSpy);

    // when
    Span.Builder resultingBuilder = builder.withTimestampedAnnotations(null);

    // then
    assertThat(resultingBuilder).isSameAs(builder);
    verifyZeroInteractions(annotationsListSpy);

    // and when
    Span resultingSpan = resultingBuilder.build();

    // then
    assertThat(resultingSpan.getTimestampedAnnotations()).isEmpty();
}
 
Example 12
Source Project: fastbreak   Source File: CircuitBreakerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void isExceptionACircuitBreakerFailure_returns_whatever_breakingEventStrategy_returns() {
    // given
    Throwable someThrowable = new Throwable();
    BreakingExceptionStrategy falseDecider = ex -> false;
    Whitebox.setInternalState(cbSpy, "breakingExceptionStrategy", falseDecider);

    // expect
    assertThat(cbSpy.isExceptionACircuitBreakerFailure(someThrowable)).isFalse();

    // and given
    BreakingExceptionStrategy trueDecider = ex -> true;
    Whitebox.setInternalState(cbSpy, "breakingExceptionStrategy", trueDecider);

    // expect
    assertThat(cbSpy.isExceptionACircuitBreakerFailure(someThrowable)).isTrue();
}
 
Example 13
Source Project: backstopper   Source File: JaxRsApiExceptionHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void beforeMethod() {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getRequestURI()).thenReturn("/fake/path");
    when(mockRequest.getMethod()).thenReturn("GET");
    when(mockRequest.getQueryString()).thenReturn("queryString");

    listenerList = new JaxRsApiExceptionHandlerListenerList(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL);

    unhandledSpy = spy(new JaxRsUnhandledExceptionHandler(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL));

    handlerSpy = spy(new JaxRsApiExceptionHandler(
        testProjectApiErrors,
        listenerList,
        ApiExceptionHandlerUtils.DEFAULT_IMPL, unhandledSpy));
    Whitebox.setInternalState(handlerSpy, "request", mockRequest);
    Whitebox.setInternalState(handlerSpy, "response", mock(HttpServletResponse.class));
}
 
Example 14
@Test
public void doGetSplits()
        throws Exception
{
    GetSplitsRequest req = mock(GetSplitsRequest.class);
    when(req.getRequestType()).thenReturn(MetadataRequestType.GET_SPLITS);
    SpillLocationVerifier mockVerifier = mock(SpillLocationVerifier.class);
    doNothing().when(mockVerifier).checkBucketAuthZ(any(String.class));
    Whitebox.setInternalState(mockMetadataHandler, "verifier", mockVerifier);
    compositeHandler.handleRequest(allocator, req, new ByteArrayOutputStream(), objectMapper);
    verify(mockMetadataHandler, times(1)).doGetSplits(any(BlockAllocatorImpl.class), any(GetSplitsRequest.class));
}
 
Example 15
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void equals_returns_false_and_hashCode_different_if_spanId_is_different() {
    // given
    Span fullSpan1 = createFilledOutSpan(true);
    Span fullSpan2 = createFilledOutSpan(true);
    Whitebox.setInternalState(fullSpan2, "spanId", fullSpan1.getSpanId() + "_nope");

    // expect
    assertThat(fullSpan1.equals(fullSpan2)).isFalse();
    assertThat(fullSpan1.hashCode()).isNotEqualTo(fullSpan2.hashCode());
}
 
Example 16
Source Project: wingtips   Source File: WingtipsSpringUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyListenableFutureCallbackWithTracing(ListenableFutureCallback result,
                                                       ListenableFutureCallback expectedCoreInstance,
                                                       Deque<Span> expectedSpanStack,
                                                       Map<String, String> expectedMdcInfo) {
    assertThat(result).isInstanceOf(ListenableFutureCallbackWithTracing.class);
    assertThat(Whitebox.getInternalState(result, "origListenableFutureCallback")).isSameAs(expectedCoreInstance);
    assertThat(Whitebox.getInternalState(result, "spanStackForExecution")).isEqualTo(expectedSpanStack);
    assertThat(Whitebox.getInternalState(result, "mdcContextMapForExecution")).isEqualTo(expectedMdcInfo);
}
 
Example 17
Source Project: wingtips   Source File: AsyncWingtipsHelperJava7Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executorServiceWithTracing_works_as_expected() {
    // when
    ExecutorServiceWithTracing result = executorServiceWithTracing(executorServiceMock);

    // then
    assertThat(Whitebox.getInternalState(result, "delegate")).isSameAs(executorServiceMock);
}
 
Example 18
Source Project: big-c   Source File: TestGraphiteMetrics.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailureAndPutMetrics() throws IOException {
  GraphiteSink sink = new GraphiteSink();
  List<MetricsTag> tags = new ArrayList<MetricsTag>();
  tags.add(new MetricsTag(MsInfo.Context, "all"));
  tags.add(new MetricsTag(MsInfo.Hostname, "host"));
  Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
  metrics.add(makeMetric("foo1", 1.25));
  metrics.add(makeMetric("foo2", 2.25));
  MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics);

  final GraphiteSink.Graphite mockGraphite = makeGraphite();
  Whitebox.setInternalState(sink, "graphite", mockGraphite);

  // throw exception when first try
  doThrow(new IOException("IO exception")).when(mockGraphite).write(anyString());

  sink.putMetrics(record);
  verify(mockGraphite).write(anyString());
  verify(mockGraphite).close();

  // reset mock and try again
  reset(mockGraphite);
  when(mockGraphite.isConnected()).thenReturn(false);

  ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
  sink.putMetrics(record);

  verify(mockGraphite).write(argument.capture());
  String result = argument.getValue();

  assertEquals(true,
      result.equals("null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n" +
      "null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n") ||
      result.equals("null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n" +
      "null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n"));
}
 
Example 19
Source Project: fastbreak   Source File: CircuitBreakerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void executeAsyncCall_does_not_time_out_the_call_if_it_takes_shorter_than_callTimeout()
    throws InterruptedException {
    // given
    long callTimeoutMillis = 100;
    long callExecutionTimeMillis = 50;
    Whitebox
        .setInternalState(cbSpy, "callTimeoutNanos", Optional.of(Duration.ofMillis(callTimeoutMillis).toNanos()));
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(callExecutionTimeMillis);
        }
        catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "foo";
    });

    // when
    long startTimeMillis = System.currentTimeMillis();
    CompletableFuture<String> result = cbSpy.executeAsyncCall(() -> future);
    Exception exThrownByFuture = null;
    try {
        result.join();
    }
    catch (Exception ex) {
        exThrownByFuture = ex;
    }
    long endTimeMillis = System.currentTimeMillis();

    // then
    Thread.sleep(callTimeoutMillis + 1); // Give the call timeout logic time to execute (if it were going to, which it shouldn't)
    assertThat(result.isCompletedExceptionally()).isFalse();
    assertThat(exThrownByFuture).isNull();
    assertThat((endTimeMillis - startTimeMillis)).isGreaterThanOrEqualTo(callExecutionTimeMillis);
}
 
Example 20
Source Project: wingtips   Source File: AsyncWingtipsHelperJava7Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void scheduledExecutorServiceWithTracing_works_as_expected() {
    // when
    ScheduledExecutorServiceWithTracing result = scheduledExecutorServiceWithTracing(scheduledExecutorServiceMock);

    // then
    assertThat(Whitebox.getInternalState(result, "delegate")).isSameAs(scheduledExecutorServiceMock);
}
 
Example 21
@Test
public void testBindGraphqlClient() {
    GraphqlClient mockClient = mock(GraphqlClient.class);
    Mockito.doReturn("my-identifier").when(mockClient).getIdentifier();

    servlet.bindGraphqlClient(mockClient, Collections.emptyMap());

    Set<String> identifiers = (Set<String>) Whitebox.getInternalState(servlet, "identifiers");
    Assert.assertEquals(1, identifiers.size());
    Assert.assertTrue(identifiers.contains("my-identifier"));
}
 
Example 22
Source Project: wingtips   Source File: AsyncWingtipsHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void executorServiceWithTracing_works_as_expected(boolean useStaticMethod) {
    // when
    ExecutorServiceWithTracing result = (useStaticMethod)
                                        ? executorServiceWithTracing(executorServiceMock)
                                        : DEFAULT_IMPL.executorServiceWithTracing(executorServiceMock);

    // then
    assertThat(Whitebox.getInternalState(result, "delegate")).isSameAs(executorServiceMock);
}
 
Example 23
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void toJson_should_use_cached_json() {
    // given
    Span validSpan = Span.generateRootSpanForNewTrace(spanName, spanPurpose).build();
    String uuidString = UUID.randomUUID().toString();
    Whitebox.setInternalState(validSpan, "cachedJsonRepresentation", uuidString);

    // when
    String toJsonResult = validSpan.toJSON();

    // then
    assertThat(toJsonResult).isEqualTo(uuidString);
}
 
Example 24
@Test
public void generateLastDitchFallbackErrorResponseInfo_returns_expected_value() {
    // given
    Exception ex = new Exception("kaboom");
    RequestInfoForLogging reqMock = mock(RequestInfoForLogging.class);
    String errorId = UUID.randomUUID().toString();
    Map<String, List<String>> headersMap = MapBuilder.builder("error_uid", singletonList(errorId)).build();

    ApiError expectedGenericError = handlerSpy.singletonGenericServiceError.iterator().next();
    int expectedHttpStatusCode = handlerSpy.genericServiceErrorHttpStatusCode;
    Map<String, List<String>> expectedHeadersMap = new HashMap<>(headersMap);
    String expectedBodyPayload = JsonUtilWithDefaultErrorContractDTOSupport.writeValueAsString(
        new DefaultErrorContractDTO(errorId, handlerSpy.singletonGenericServiceError)
    );

    // when
    ErrorResponseInfo<Mono<ServerResponse>> result = handlerSpy.generateLastDitchFallbackErrorResponseInfo(
        ex, reqMock, errorId, headersMap
    );

    // then
    assertThat(result.httpStatusCode).isEqualTo(expectedHttpStatusCode);
    assertThat(result.headersToAddToResponse).isEqualTo(expectedHeadersMap);
    ServerResponse serverResponse = result.frameworkRepresentationObj.block();
    assertThat(serverResponse.statusCode().value()).isEqualTo(expectedHttpStatusCode);
    assertThat(serverResponse.headers().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
    // Yes this is awful. But figuring out how to spit out the ServerResponse's body to something assertable
    //      in this test is also awful.
    assertThat(Whitebox.getInternalState(serverResponse, "entity")).isEqualTo(expectedBodyPayload);
}
 
Example 25
@Test
public void constructor_sets_projectApiErrors_and_utils_to_passed_in_args() {
    // given
    ProjectApiErrors projectErrorsMock = mock(ProjectApiErrors.class);
    ApiExceptionHandlerUtils utilsMock = mock(ApiExceptionHandlerUtils.class);

    // when
    OneOffSpringWebFluxFrameworkExceptionHandlerListener
        impl = new OneOffSpringWebFluxFrameworkExceptionHandlerListener(projectErrorsMock, utilsMock);

    // then
    assertThat(Whitebox.getInternalState(impl, "projectApiErrors")).isSameAs(projectErrorsMock);
    assertThat(Whitebox.getInternalState(impl, "utils")).isSameAs(utilsMock);
}
 
Example 26
Source Project: fastbreak   Source File: CircuitBreakerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void throwExceptionIfCircuitBreakerIsOpen_throws_CircuitBreakerOpenException_if_circuit_is_OPEN() {
    // given
    Whitebox.setInternalState(cbSpy, "currentState", State.OPEN);

    // when
    Throwable cbExplosion = catchThrowable(cbSpy::throwExceptionIfCircuitBreakerIsOpen);

    // then
    assertThat(cbExplosion).isNotNull();
    assertThat(cbExplosion).isInstanceOf(CircuitBreakerOpenException.class);
    verify(cbSpy, times(0)).scheduleHalfOpenStateTimeout();
}
 
Example 27
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void equals_returns_false_and_hashCode_different_if_traceId_is_different() {
    // given
    Span fullSpan1 = createFilledOutSpan(true);
    Span fullSpan2 = createFilledOutSpan(true);
    Whitebox.setInternalState(fullSpan2, "traceId", fullSpan1.getTraceId() + "_nope");

    // expect
    assertThat(fullSpan1.equals(fullSpan2)).isFalse();
    assertThat(fullSpan1.hashCode()).isNotEqualTo(fullSpan2.hashCode());
}
 
Example 28
Source Project: aem-core-cif-components   Source File: ProductImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSafeDescriptionConfigurableProduct() {
    productModel = context.request().adaptTo(ProductImpl.class);
    String sampleString = "<strong>def</strong>";
    ConfigurableProduct product = mock(ConfigurableProduct.class, RETURNS_DEEP_STUBS);
    ComplexTextValue value = mock(ComplexTextValue.class, RETURNS_DEEP_STUBS);
    when(value.getHtml()).thenReturn(sampleString);
    when(product.getDescription()).thenReturn(value);

    Whitebox.setInternalState(productModel.getProductRetriever(), "product", product);

    Assert.assertEquals(sampleString, productModel.getDescription());
}
 
Example 29
Source Project: wingtips   Source File: SpanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void equals_returns_false_and_hashCode_different_if_spanName_is_different() {
    // given
    Span fullSpan1 = createFilledOutSpan(true);
    Span fullSpan2 = createFilledOutSpan(true);
    Whitebox.setInternalState(fullSpan2, "spanName", fullSpan1.getSpanName() + "_nope");

    // expect
    assertThat(fullSpan1.equals(fullSpan2)).isFalse();
    assertThat(fullSpan1.hashCode()).isNotEqualTo(fullSpan2.hashCode());
}
 
Example 30
Source Project: aem-core-cif-components   Source File: SearchBarImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearchResultPage() {
    SearchbarImpl searchbar = new SearchbarImpl();

    Whitebox.setInternalState(searchbar, "currentPage", context.currentPage("/content/pageA"));

    Assert.assertEquals("/content/pageB.html", searchbar.getSearchResultsPageUrl());
}