Java Code Examples for org.junit.Assert#assertThat()

The following examples show how to use org.junit.Assert#assertThat() . 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
public void actualTest(AppiumDriver driver) {
    // Set up default wait
    WebDriverWait wait = new WebDriverWait(driver, 10);

    try {
        driver.get("http://appiumpro.com/contact");
        wait.until(ExpectedConditions.visibilityOfElementLocated(EMAIL))
            .sendKeys("[email protected]");
        driver.findElement(MESSAGE).sendKeys("Hello!");
        driver.findElement(SEND).click();
        String response = wait.until(ExpectedConditions.visibilityOfElementLocated(ERROR)).getText();

        // validate that we get an error message involving a captcha, which we didn't fill out
        Assert.assertThat(response, CoreMatchers.containsString("Captcha"));
    } finally {
        driver.quit();
    }

}
 
Example 2
Source Project: fuzzy-matcher   File: MatchServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void itShouldApplyMatchForMultiplePhoneNumber() {
    List<Document> inputData = new ArrayList<>();
    inputData.add(new Document.Builder("1")
            .addElement(new Element.Builder().setType(NAME).setValue("Kapa Limited").createElement())
            .addElement(new Element.Builder().setType(ADDRESS).setValue("texas").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("8204354957 xyz").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("(848) 398-3868").createElement())
            .addElement(new Element.Builder().setType(EMAIL).setValue("[email protected]").createElement())
            .createDocument());
    inputData.add(new Document.Builder("2")
            .addElement(new Element.Builder().setType(NAME).setValue("Tram Kapa Ltd LLC").createElement())
            .addElement(new Element.Builder().setType(ADDRESS).setValue("texas").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("(848) 398-3868").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("(820) 435-4957").createElement())
            .addElement(new Element.Builder().setType(PHONE).setValue("").createElement())
            .addElement(new Element.Builder().setType(EMAIL).setValue("[email protected]").createElement())
            .createDocument());
    Map<Document, List<Match<Document>>> result = matchService.applyMatch(inputData);
    Assert.assertEquals(2, result.size());
    Assert.assertThat(result.entrySet().stream()
                    .map(entry -> entry.getKey().getKey()).collect(Collectors.toList()),
            CoreMatchers.hasItems("1", "2"));
}
 
Example 3
@Test
public void testIsNotNull() throws Exception {
    String simpleQuery = "SELECT col0 IS NOT NULL FROM CODEGEN_TEST;";
    Analysis analysis = analyzeQuery(simpleQuery);

    ExpressionMetadata expressionEvaluatorMetadata0 = codeGenRunner.buildCodeGenFromParseTree
        (analysis.getSelectExpressions().get(0));
    assertThat(expressionEvaluatorMetadata0.getIndexes().length, equalTo(1));
    int idx0 = expressionEvaluatorMetadata0.getIndexes()[0];
    assertThat(idx0, equalTo(0));
    assertThat(expressionEvaluatorMetadata0.getUdfs().length, equalTo(1));

    Object result0 = expressionEvaluatorMetadata0.getExpressionEvaluator().evaluate(new Object[]{null});
    assertThat(result0, instanceOf(Boolean.class));
    Assert.assertThat((Boolean)result0, is(false));

    result0 = expressionEvaluatorMetadata0.getExpressionEvaluator().evaluate(new Object[]{12345L});
    assertThat(result0, instanceOf(Boolean.class));
    assertThat((Boolean)result0, is(true));
}
 
Example 4
Source Project: nalu   File: RouteParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void parse22() {
  String route = "/application/person/detail/";
  try {
    RouteResult routeResult = RouteParser.get()
                                         .parse(route,
                                                this.shellConfiguration,
                                                this.routerConfiguration);
    Assert.assertThat(routeResult.getShell(),
                      is("/application"));
    Assert.assertThat(routeResult.getRoute(),
                      is("/application/person/detail/*"));
    Assert.assertThat(routeResult.getParameterValues()
                                 .get(0),
                      is(""));
  } catch (RouterException e) {
    throw new AssertionError("no exception expected here!",
                             e);
  }
}
 
Example 5
@Test
public void createResponseMapper() {
  Method responseEntityMethod = ReflectUtils.findMethod(this.getClass(), "responseEntity");

  ProducerResponseMapper mapper = factory
      .createResponseMapper(factorys, responseEntityMethod.getGenericReturnType());
  Assert.assertThat(mapper, Matchers.instanceOf(SpringmvcProducerResponseMapper.class));

  ResponseEntity<String[]> responseEntity = new ResponseEntity<>(new String[] {"a", "b"}, HttpStatus.OK);
  Response response = mapper.mapResponse(null, responseEntity);
  Assert.assertThat(response.getResult(), Matchers.arrayContaining("a", "b"));
}
 
Example 6
@Test public void buildUriString() {
  String uriString = UriBuilder.
      buildUriString(tokenContractAddress, iabContractAddress,
          new BigDecimal("1000000000000000000"), developerAddress, "com.cenas.product", 3);

  Assert.assertThat(uriString,
      is("ethereum:[email protected]/buy?uint256=1000000000000000000&address=0x4fbcc5ce88493c3d9903701c143af65f54481119&data=0x636f6d2e63656e61732e70726f64756374&iabContractAddress=0xb015D9bBabc472BBfC990ED6A0C961a90a482C57"));
}
 
Example 7
@Test
public void assertNew() {
    ShardingContexts shardingContexts = ShardingContextsBuilder.getMultipleShardingContexts();
    ShardingContext actual = new ShardingContext(shardingContexts, 1);
    Assert.assertThat(actual.getJobName(), Is.is(shardingContexts.getJobName()));
    Assert.assertThat(actual.getTaskId(), Is.is(shardingContexts.getTaskId()));
    Assert.assertThat(actual.getShardingTotalCount(), Is.is(shardingContexts.getShardingTotalCount()));
    Assert.assertThat(actual.getJobParameter(), Is.is(shardingContexts.getJobParameter()));
    Assert.assertThat(actual.getShardingItem(), Is.is(1));
    Assert.assertThat(actual.getShardingParameter(), Is.is(shardingContexts.getShardingItemParameters().get(1)));
}
 
Example 8
@Test
public void resolveI18nFullLocale() throws Exception {
	LocaleContextHolder.setLocale(Locale.GERMANY);
	URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl");
	Assert.assertNotNull(url);
	Assert.assertThat(url.getPath(), Matchers.containsString("i18n_de_DE.tpl"));
}
 
Example 9
@Test
public void xsuaaMockStarted() throws URISyntaxException {
	ResponseEntity<String> response = restTemplate.getForEntity(
			new URI(xsuaaServiceConfiguration.getUaaUrl() + "/token_keys"),
			String.class);
	Assert.assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
	Assert.assertThat(response.getBody(), notNullValue());
}
 
Example 10
@Test
public void resolveI18nFullLocale() throws Exception {
	LocaleContextHolder.setLocale(Locale.GERMANY);
	URL url = this.configurer.resolveTemplate(getClass().getClassLoader(), TEMPLATE_PREFIX + "i18n.tpl");
	Assert.assertNotNull(url);
	Assert.assertThat(url.getPath(), Matchers.containsString("i18n_de_DE.tpl"));
}
 
Example 11
Source Project: pipeline-maven-plugin   File: XmlUtilsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test_getExecutedLifecyclePhases() throws Exception {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/jenkinsci/plugins/pipeline/maven/maven-spy-package-jar.xml");
    in.getClass(); // check non null
    Element mavenSpyLogs = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in).getDocumentElement();
    List<String> executedLifecyclePhases = XmlUtils.getExecutedLifecyclePhases(mavenSpyLogs);
    System.out.println(executedLifecyclePhases);
    Assert.assertThat(executedLifecyclePhases, Matchers.contains("process-resources", "compile", "process-test-resources", "test-compile", "test", "package"));
}
 
Example 12
Source Project: sf-java-ui   File: TabbedFormTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testGenerate_TabbedFormed() throws JsonProcessingException{
	UiForm ui = UiFormSchemaGenerator.get().generate(TabbedForm.class);

	String json = new ObjectMapper().writeValueAsString(ui);
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)]"));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)].tabs[*]", hasSize(2)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)].tabs[0].title",hasItem("Info")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)].tabs[1].title",hasItem("Contact")));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)].tabs[?(@.title=='Info')].items[*]",hasSize(2)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.tabs)].tabs[?(@.title=='Contact')].items[*]",hasSize(1)));
	Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='webSite')]"));
}
 
Example 13
@Test
public void testGeneratedListOfListOfList() {
    logger.debug("testGeneratedListOfListOfList");
    Object objectType = generator.getOutputType(ClassWithListOfListOfList.class);
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition field = ((GraphQLObjectType) objectType)
            .getFieldDefinition("listOfListOfListOfInts");
    
    Assert.assertThat(field, notNullValue());
    GraphQLOutputType listType = field.getType();
    Assert.assertThat(listType, instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) listType).getWrappedType();
    assertListOfListOfInt(wrappedType);
}
 
Example 14
@Test
public void assertFindLatestTaskResultStatisticsWhenRdbIsConfigured() throws NoSuchFieldException {
    ReflectionUtils.setFieldValue(statisticManager, "rdbRepository", rdbRepository);
    for (StatisticInterval each : StatisticInterval.values()) {
        Mockito.when(rdbRepository.findLatestTaskResultStatistics(each))
            .thenReturn(Optional.of(new TaskResultStatistics(10, 5, each, new Date())));
        TaskResultStatistics actual = statisticManager.findLatestTaskResultStatistics(each);
        Assert.assertThat(actual.getSuccessCount(), Is.is(10));
        Assert.assertThat(actual.getFailedCount(), Is.is(5));
    }
    Mockito.verify(rdbRepository, Mockito.times(StatisticInterval.values().length)).findLatestTaskResultStatistics(Mockito.any(StatisticInterval.class));
}
 
Example 15
@Test
public void assertLoadWithConfig() {
    Mockito.when(regCenter.get("/config/app/test_app")).thenReturn(CloudAppJsonConstants.getAppJson("test_app"));
    Optional<CloudAppConfiguration> actual = configService.load("test_app");
    Assert.assertTrue(actual.isPresent());
    Assert.assertThat(actual.get().getAppName(), Is.is("test_app"));
}
 
Example 16
Source Project: flink   File: ReporterSetupTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReporterSetupSupplier() throws Exception {
	final Configuration config = new Configuration();

	config.setString(ConfigConstants.METRICS_REPORTER_PREFIX + "reporter1." + ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, TestReporter1.class.getName());

	final List<ReporterSetup> reporterSetups = ReporterSetup.fromConfiguration(config);

	Assert.assertEquals(1, reporterSetups.size());

	final ReporterSetup reporterSetup = reporterSetups.get(0);
	final MetricReporter metricReporter = reporterSetup.getReporter();
	Assert.assertThat(metricReporter, instanceOf(TestReporter1.class));
}
 
Example 17
Source Project: Jose4j   File: JwtClaimsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubject() throws InvalidJwtException, MalformedClaimException
{
    String sub = "[email protected]";
    JwtClaims claims = JwtClaims.parse("{\"sub\":\"" + sub + "\"}");
    Assert.assertThat(sub, equalTo(claims.getSubject()));
}
 
Example 18
@Test
public void testGetValueContainerType() throws Exception {
  new Expectations() {
    {
      request.getParameterValues("name");
      result = new String[] {"value", "value2"};
    }
  };

  ParamValueProcessor processor = createProcessor("name", String[].class, "multi");
  String[] value = (String[]) processor.getValue(request);
  Assert.assertThat(value, Matchers.arrayContaining("value", "value2"));
}
 
Example 19
@Test
public void testOfCollection() {
	Assert.assertThat(Optionals.of(Arrays.asList(1, 2)), isPresentAnd(hasSize(2)));
	Assert.assertThat(Optionals.of(Arrays.asList(1, 2)), isPresentAnd(hasItems(1, 2)));
}
 
Example 20
Source Project: Tomcat8-Source-Read   File: TestHttp2Limits.java    License: MIT License 4 votes vote down vote up
private void doTestPostWithTrailerHeaders(int maxTrailerCount, int maxTrailerSize,
        FailureMode failMode) throws Exception {
    enableHttp2();

    http2Protocol.setAllowedTrailerHeaders(TRAILER_HEADER_NAME);
    http2Protocol.setMaxTrailerCount(maxTrailerCount);
    http2Protocol.setMaxTrailerSize(maxTrailerSize);

    configureAndStartWebApplication();
    openClientConnection();
    doHttpUpgrade();
    sendClientPreface();
    validateHttp2InitialResponse();

    byte[] headersFrameHeader = new byte[9];
    ByteBuffer headersPayload = ByteBuffer.allocate(128);
    byte[] dataFrameHeader = new byte[9];
    ByteBuffer dataPayload = ByteBuffer.allocate(256);
    byte[] trailerFrameHeader = new byte[9];
    ByteBuffer trailerPayload = ByteBuffer.allocate(256);

    buildPostRequest(headersFrameHeader, headersPayload, false, dataFrameHeader, dataPayload,
            null, trailerFrameHeader, trailerPayload, 3);

    // Write the headers
    writeFrame(headersFrameHeader, headersPayload);
    // Body
    writeFrame(dataFrameHeader, dataPayload);
    // Trailers
    writeFrame(trailerFrameHeader, trailerPayload);

    switch (failMode) {
    case NONE: {
        parser.readFrame(true);
        parser.readFrame(true);
        parser.readFrame(true);
        parser.readFrame(true);

        String len = Integer.toString(256 + TRAILER_HEADER_VALUE.length());

        Assert.assertEquals("0-WindowSize-[256]\n" +
                "3-WindowSize-[256]\n" +
                "3-HeadersStart\n" +
                "3-Header-[:status]-[200]\n" +
                "3-Header-[content-length]-[" + len + "]\n" +
                "3-Header-[date]-["+ DEFAULT_DATE + "]\n" +
                "3-HeadersEnd\n" +
                "3-Body-" +
                len +
                "\n" +
                "3-EndOfStream\n",
                output.getTrace());
        break;
    }
    case STREAM_RESET: {
        // NIO2 can sometimes send window updates depending timing
        skipWindowSizeFrames();

        Assert.assertEquals("3-RST-[11]\n", output.getTrace());
        break;
    }
    case CONNECTION_RESET: {
        // NIO2 can sometimes send window updates depending timing
        skipWindowSizeFrames();

        // This message uses i18n and needs to be used in a regular
        // expression (since we don't know the connection ID). Generate the
        // string as a regular expression and then replace '[' and ']' with
        // the escaped values.
        String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\d++", "3");
        limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
        Assert.assertThat(output.getTrace(), RegexMatcher.matchesRegex(
                "0-Goaway-\\[3\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
        break;
    }
    }
}