org.junit.jupiter.api.Test Java Examples
The following examples show how to use
org.junit.jupiter.api.Test.
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: AshotFactoryTests.java From vividus with Apache License 2.0 | 6 votes |
@Test void shouldCreateAshotUsingScrollableElement() { WebElement webElement = mock(WebElement.class); ScreenshotConfiguration screenshotConfiguration = new ScreenshotConfiguration(); screenshotConfiguration.setScrollableElement(() -> Optional.of(webElement)); screenshotConfiguration.setCoordsProvider("CEILING"); screenshotConfiguration.setScreenshotShootingStrategy(Optional.empty()); AShot aShot = ashotFactory.create(false, Optional.of(screenshotConfiguration)); assertThat(Whitebox.getInternalState(aShot, COORDS_PROVIDER), is(instanceOf(CeilingJsCoordsProvider.class))); ShootingStrategy scrollableElementAwareDecorator = getShootingStrategy(aShot); assertThat(scrollableElementAwareDecorator, is(instanceOf(AdjustingScrollableElementAwareViewportPastingDecorator.class))); assertEquals(webElement, Whitebox.getInternalState(scrollableElementAwareDecorator, "scrollableElement")); ShootingStrategy scalingDecorator = getShootingStrategy(scrollableElementAwareDecorator); assertThat(scalingDecorator, is(instanceOf(ScalingDecorator.class))); verifyDPR(scalingDecorator); }
Example #2
Source File: ExpressionAdapterTests.java From vividus with Apache License 2.0 | 6 votes |
@Test void testMixedValuesInExampleTable() { when(mockedAnotherProcessor.execute(UNSUPPORTED_EXPRESSION_KEYWORD)).thenReturn(Optional.empty()); when(mockedTargetProcessor.execute(UNSUPPORTED_EXPRESSION_KEYWORD)).thenReturn(Optional.empty()); when(mockedTargetProcessor.execute(EXPRESSION_KEYWORD)).thenReturn(Optional.of(EXPRESSION_RESULT)); when(mockedTargetProcessor.execute(EXPRESSION_KEYWORD_WITH_SEPARATOR)) .thenReturn(Optional.of(EXPRESSION_RESULT)); expressionAdaptor.setProcessors(List.of(mockedTargetProcessor, mockedAnotherProcessor)); String anotherExpressionKeyword = "another"; when(mockedAnotherProcessor.execute(anotherExpressionKeyword)).thenReturn(Optional.of("another result")); String header = "|value1|value2|value3|value4|value5|\n"; String inputTable = header + "|#{unsupported}|simple|#{target}|#{tar\nget}|#{another}|"; String expectedTable = header + "|#{unsupported}|simple|target result with \\ and $|target result with \\ and" + " $|another result|"; String actualTable = expressionAdaptor.process(inputTable); assertEquals(expectedTable, actualTable); }
Example #3
Source File: BuildParameterBuilderTest.java From smithy with Apache License 2.0 | 6 votes |
@Test public void ignoresNullAndEmptyValues() { BuildParameterBuilder.Result result = new BuildParameterBuilder() .sources(null) .projectionSource(null) .projectionSource("") .projectionSourceTags((String) null) .projectionSourceTags((Collection<String>) null) .addConfig(null) .addConfig("") .addConfigIfExists(null) .addConfigIfExists("") .buildClasspath(null) .buildClasspath("") .libClasspath(null) .libClasspath("") .build(); assertThat(result.args, contains("build")); assertThat(result.classpath.length(), is(0)); assertThat(result.discoveryClasspath.length(), is(0)); assertThat(result.sources, empty()); }
Example #4
Source File: TestParameterizableStringListFactory.java From quaerite with Apache License 2.0 | 6 votes |
@Test public void testFormats() { String paramString = "[-.0000000001]"; ParameterizableStringFactory<TestParam> fact = new ParameterizableStringFactory("bf", "0", TestParam.class, paramString); assertEquals("-1.0E-10", fact.random().toString()); paramString = "[5000.1]"; fact = new ParameterizableStringFactory("bf", "0", TestParam.class, paramString); assertEquals("5000.1", fact.random().toString()); paramString = "[10.123423]"; fact = new ParameterizableStringFactory("bf", "0", TestParam.class, paramString); assertEquals("10.123", fact.random().toString()); paramString = "[0.123423]"; fact = new ParameterizableStringFactory("bf", "0", TestParam.class, paramString); assertEquals("0.123", fact.random().toString()); paramString = "[7.1]"; fact = new ParameterizableStringFactory("bf", "0", TestParam.class, paramString); assertEquals("7.1", fact.random().toString()); }
Example #5
Source File: NestedAccessorsTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testDoubleNestedAccessor() throws Exception { final String str = "import org.drools.compiler.*;\n" + "rule R1 when\n" + " Person( name == \"mark\", cheese.(price == 10, type.(length == 10) ) )\n" + "then\n" + "end\n"; final KieBase kbase = loadKnowledgeBaseFromString(str); final KieSession ksession = kbase.newKieSession(); final Person mark1 = new Person("mark"); mark1.setCheese(new Cheese("gorgonzola", 10)); ksession.insert(mark1); assertEquals(1, ksession.fireAllRules()); ksession.dispose(); }
Example #6
Source File: CacheTests.java From chart-fx with Apache License 2.0 | 6 votes |
@Test public void testHelperMethods() { // TimeUnit to ChronoUnit conversions for (TimeUnit timeUnit : TimeUnit.values()) { ChronoUnit chronoUnit = Cache.convertToChronoUnit(timeUnit); // timeUnit.toChronoUnit() would be faster but exists only since Java 9 long nanoTimeUnit = timeUnit.toNanos(1); long nanoChrono = chronoUnit.getDuration().getNano() + 1000000000 * chronoUnit.getDuration().getSeconds(); assertEquals(nanoTimeUnit, nanoChrono, "ChronoUnit =" + chronoUnit); } // test clamp(int ... ) routine assertEquals(1, Cache.clamp(1, 3, 0)); assertEquals(2, Cache.clamp(1, 3, 2)); assertEquals(3, Cache.clamp(1, 3, 4)); // test clamp(long ... ) routine assertEquals(1l, Cache.clamp(1l, 3l, 0l)); assertEquals(2l, Cache.clamp(1l, 3l, 2l)); assertEquals(3l, Cache.clamp(1l, 3l, 4l)); }
Example #7
Source File: DragResizerUtilTests.java From chart-fx with Apache License 2.0 | 6 votes |
@Test public void testResizeHandler() { final Rectangle rect = new Rectangle(/* minX */ 0.0, /* minY */ 0.0, /* width */ 100.0, /* height */ 50.0); assertDoesNotThrow(() -> DragResizerUtil.DEFAULT_LISTENER.onDrag(rect, 0, 0, 10, 20)); assertEquals(10, rect.getWidth()); assertEquals(20, rect.getHeight()); assertDoesNotThrow(() -> DragResizerUtil.DEFAULT_LISTENER.onResize(rect, 0, 0, 11, 21)); assertEquals(11, rect.getWidth()); assertEquals(21, rect.getHeight()); final Canvas canvas = new Canvas(100, 50); assertDoesNotThrow(() -> DragResizerUtil.DEFAULT_LISTENER.onDrag(canvas, 0, 0, 10, 20)); assertEquals(10, canvas.getWidth()); assertEquals(20, canvas.getHeight()); final Region region = new Region(); region.setMinSize(100, 50); assertDoesNotThrow(() -> DragResizerUtil.DEFAULT_LISTENER.onDrag(region, 0, 0, 10, 20)); assertEquals(10, region.getPrefWidth()); assertEquals(20, region.getPrefHeight()); }
Example #8
Source File: ByteBufferWriterTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@Test void shouldWriteUInt256Integers() { ByteBuffer buffer = ByteBuffer.allocate(64); SSZ.encodeTo(buffer, writer -> writer.writeUInt256(UInt256.valueOf(100000L))); buffer.flip(); assertEquals( fromHexString("A086010000000000000000000000000000000000000000000000000000000000"), Bytes.wrapByteBuffer(buffer)); buffer.clear(); SSZ .encodeTo( buffer, writer -> writer .writeUInt256( UInt256.fromHexString("0x0400000000000000000000000000000000000000000000000000f100000000ab"))); buffer.flip(); assertEquals( fromHexString("AB00000000F10000000000000000000000000000000000000000000000000004"), Bytes.wrapByteBuffer(buffer)); }
Example #9
Source File: TestKata2LambdasDeeperDive.java From java-katas with MIT License | 6 votes |
@Test @Tag("TODO") @Order(4) public void sortNames() { List<Person> persons = Arrays.asList(Person.ALICE, Person.BOB, Person.CATHY, Person.DHRUV, Person.EMILY); List<Person> expectedList = Arrays.asList(Person.EMILY, Person.BOB, Person.DHRUV, Person.ALICE, Person.CATHY); // TODO: // Replace the anonymous class with a lambda. // Replace the postions of o2 and o1 to pass the test as well Comparator<Person> nameSorter = new Comparator<>() { @Override public int compare(Person o1, Person o2) { return o2.getLastName().compareTo(o1.getLastName()); } }; List<Person> actualList = new ArrayList<>(); actualList.addAll(persons); Collections.sort(actualList, nameSorter); assertEquals(expectedList, actualList, "The sorted lists should match"); }
Example #10
Source File: RuleParserTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testBindingComposite() throws Exception { final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; PatternDescr pattern = (PatternDescr) ((RuleDescr) parse( "rule", text )).getLhs().getDescrs().get( 0 ); assertEquals( "Person", pattern.getObjectType() ); assertFalse( pattern.isUnification() ); // assertEquals( 2, // pattern.getDescrs().size() ); // BindingDescr bindingDescr = pattern.getDescrs().get( 0 ); // assertEquals( "$name", // bindingDescr.getVariable() ); // assertEquals( "name", // bindingDescr.getExpression() ); // assertFalse( bindingDescr.isUnification() ); // // bindingDescr = pattern.getDescrs().get( 1 ); // assertEquals( "$loc", // bindingDescr.getVariable() ); // assertEquals( "location", // bindingDescr.getExpression() ); // assertFalse( bindingDescr.isUnification() ); // embedded bindings are extracted at compile time List< ? > constraints = pattern.getDescrs(); assertEquals( 1, constraints.size() ); assertEquals( "$name : name == \"Bob\" || $loc : location == \"Montreal\"", ((ExprConstraintDescr) constraints.get( 0 )).getExpression() ); }
Example #11
Source File: CommandlineParserClientTlsOptionsTest.java From ethsigner with Apache License 2.0 | 5 votes |
@Test void downstreamKnownServerIsNotRequiredIfCaSignedEnabledExplicitly() { List<String> cmdLine = modifyField(validBaseCommandOptions(), "downstream-http-tls-ca-auth-enabled", "true"); cmdLine = removeFieldsFrom(cmdLine, "downstream-http-tls-known-servers-file"); cmdLine.add(subCommand.getCommandName()); final boolean result = parser.parseCommandLine(cmdLine.toArray(String[]::new)); assertThat(result).as("CLI Parse result").isTrue(); final Optional<ClientTlsOptions> optionalDownstreamTlsOptions = config.getClientTlsOptions(); assertThat(optionalDownstreamTlsOptions.isPresent()).as("Downstream TLS Options").isTrue(); }
Example #12
Source File: GeneratorBehavior.java From smallrye-graphql with Apache License 2.0 | 5 votes |
@Test public void shouldGenerateApiForOneSimpleQuery() { Generator generator = givenGeneratorFor(HEROES); Map<String, String> generatedFiles = generator.generateSourceFiles(); thenContainsExactly(generatedFiles, generatedApiWith("import java.util.List;\n\n", HEROES_METHOD), CLASS_SUPER_HERO_WITH_REAL_NAME); }
Example #13
Source File: FluentPathTests.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
@Test public void testSkip() throws FileNotFoundException, FHIRFormatError, IOException, FHIRException { testBoolean(patient(), "(0 | 1 | 2).skip(1) = 1 | 2", true); testBoolean(patient(), "(0 | 1 | 2).skip(2) = 2", true); testBoolean(patient(), "Patient.name.skip(1).given = 'Jim'", true); testBoolean(patient(), "Patient.name.skip(2).given.exists() = false", true); }
Example #14
Source File: LocatorUtilTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testGetXpathPatternWithNormalizationAndTraslateFromWebElement() { By expectedLocator = By.xpath(".//a[text()[normalize-space(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'," + " 'abcdefghijklmnopqrstuvwxyz'))=\"what's great about it\"]" + " or *[normalize-space(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'," + " 'abcdefghijklmnopqrstuvwxyz'))=\"what's great about it\"]]"); By actualLocator = LocatorUtil.getXPathLocator( ".//a[text()[translate(.," + " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '%1$s'] or *[translate(.," + " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = '%1$s']]", "what's great about it"); assertEquals(expectedLocator, actualLocator); }
Example #15
Source File: MultiKeyHashicorpTransactionSignerAcceptanceTest.java From ethsigner with Apache License 2.0 | 5 votes |
@Test void hashicorpLoadedFromMultiKeyCanSignValueTransferTransaction(@TempDir Path tomlDirectory) { createHashicorpTomlFileAt(tomlDirectory.resolve(FILENAME + ".toml"), hashicorpNode); setup(tomlDirectory); performTransaction(); }
Example #16
Source File: ZerosTest.java From java with Apache License 2.0 | 5 votes |
@Test public void createStringZeros() { try (Graph g = new Graph(); Session sess = new Session(g)) { Scope scope = new Scope(g); long[] shape = {2, 2}; Zeros<TString> op = Zeros.create(scope, Constant.vectorOf(scope, shape), TString.DTYPE); try (Tensor<TString> result = sess.runner().fetch(op.asOutput()).run().get(0).expect(TString.DTYPE)) { result.data().scalars().forEach(s -> assertTrue(s.getObject().isEmpty())); } } }
Example #17
Source File: VertxRLPxServiceTest.java From incubator-tuweni with Apache License 2.0 | 5 votes |
@Test void stopServiceWithoutStartingItFirst(@VertxInstance Vertx vertx) { VertxRLPxService service = new VertxRLPxService(vertx, 0, "localhost", 10000, SECP256K1.KeyPair.random(), new ArrayList<>(), "abc"); AsyncCompletion completion = service.stop(); assertTrue(completion.isDone()); }
Example #18
Source File: TestBadMethodAccessModifiers.java From Box with Apache License 2.0 | 5 votes |
@Test public void test() { ClassNode cls = getClassNodeFromSmaliFiles("others", "TestBadMethodAccessModifiers", "TestCls"); String code = cls.getCode().toString(); assertThat(code, not(containsString("protected void test() {"))); assertThat(code, containsOne("public void test() {")); }
Example #19
Source File: TestKata3PeriodsAndDurations.java From java-katas with MIT License | 5 votes |
@Test @Tag("TODO") @Order(3) public void verifyDurationCreatedUsingIntegersAndChronoUnits() { // Create a Duration instance // TODO: Replace the Duration.ZERO to a duration of 3 hours and 6 seconds. // Check: java.time.Duration.of(int, ChronoUnit) Duration threeHoursAndSixSeconds = Duration.ZERO; assertEquals(3, threeHoursAndSixSeconds.toHours(), "The time duration should include three hours."); assertEquals(10806, threeHoursAndSixSeconds.getSeconds(), "The time duration should include three hours and six seconds in seconds."); // Add the Duration to a LocalDateTime LocalDateTime tOJDateTime = LocalDateTime.now(terminatorOriginalJudgementDay); // TODO: Call a method on tOJDateTime to add the newly created Duration // Check : java.time.LocalDateTime.plus(java.time.temporal.TemporalAmount) LocalDateTime calculatedThreeHoursAndSixSecondsLater = tOJDateTime; //7:14:30 GMT = 2:14:30 in (GMT-5). Adding 3h 6s = 5:14:36 in (GMT-5) assertEquals(5, calculatedThreeHoursAndSixSecondsLater.getHour(), "The hour after 3 hours and six seconds should be 5."); assertEquals(14, calculatedThreeHoursAndSixSecondsLater.getMinute(), "The minute after 3 hours and six seconds should be 14."); assertEquals(36, calculatedThreeHoursAndSixSecondsLater.getSecond(), "The second after 3 hours and six seconds should be 36."); }
Example #20
Source File: SmithyTestSuiteTest.java From smithy with Apache License 2.0 | 5 votes |
@Test public void throwsWhenFailed() { try { SmithyTestSuite.runner() .addTestCasesFromUrl(getClass().getResource("testrunner/invalid")) .run(); Assertions.fail("Expected to throw"); } catch (SmithyTestSuite.Error e) { assertThat(e.result.getSuccessCount(), is(1)); assertThat(e.result.getFailedResults().size(), is(2)); assertThat(e.getMessage(), containsString("Did not match the")); assertThat(e.getMessage(), containsString("Encountered unexpected")); } }
Example #21
Source File: RuleMetadataTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testRetract() { String rule1 = "retract( $b );"; KieBase kbase = getKnowledgeBase(rule1); RuleImpl rule = getRule(kbase, "R0"); ConsequenceMetaData consequenceMetaData = rule.getConsequenceMetaData(); assertEquals(1, consequenceMetaData.getStatements().size()); ConsequenceMetaData.Statement statment = consequenceMetaData.getStatements().get(0); assertEquals(ConsequenceMetaData.Statement.Type.RETRACT, statment.getType()); assertEquals(RuleMetadataTest.B.class.getName(), statment.getFactClassName()); }
Example #22
Source File: TestPointExpireStrategy.java From hyena with Apache License 2.0 | 5 votes |
@Test public void test_expirePoint() throws InterruptedException { ListPointRecParam param = new ListPointRecParam(); param.setUid(super.getUid())//.setSubUid(super.getSubUid()) .setType(super.getPointType()).setStart(0L).setSize(1); Thread.sleep(100L); List<PointPo> pointList = this.pointDs.listExpirePoint(param); PointPo point = pointList.get(0); BigDecimal number = point.getAvailable(); BigDecimal resultAvailable = this.point.getPoint().subtract(number); PointUsage usage = new PointUsage(); usage.setType(super.getPointType())//.setRecId(rec.getId()) .setUid(super.getUid())//.setSubUid(super.getSubUid()) .setPoint(number).setNote("test_expirePoint"); PointPo result = this.pointExpireStrategy.process(usage); logger.info("result = {}", result); Assertions.assertEquals(this.point.getPoint().subtract(number), result.getPoint()); Assertions.assertEquals(resultAvailable, result.getAvailable()); Assertions.assertEquals(DecimalUtils.ZERO, result.getUsed()); Assertions.assertEquals(DecimalUtils.ZERO, result.getFrozen()); Assertions.assertEquals(number, result.getExpire()); Thread.sleep(100L); PointRecPo resultRec = this.pointRecDs.getById(super.getPointType(), rec.getId(), false); logger.info("resultRec = {}", resultRec); Assertions.assertFalse(resultRec.getEnable()); Assertions.assertTrue(resultRec.getAvailable().longValue() == 0L); Assertions.assertTrue(resultRec.getExpire() == number); }
Example #23
Source File: MapUtilsTest.java From smithy with Apache License 2.0 | 5 votes |
@Test public void collectsToMap() { Map<String, String> map = Stream.of("Jason", "Michael", "Kevin") .collect(MapUtils.toUnmodifiableMap(i -> i.substring(0, 1), identity())); assertThat(map, hasEntry("J", "Jason")); assertThat(map, hasEntry("K", "Kevin")); assertThat(map, hasEntry("M", "Michael")); }
Example #24
Source File: JavascriptActionsTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testOnLoadBrowserConfig() { mockScriptExecution(GET_BROWSER_CONFIG_JS, BROWSER_CONFIG); javascriptActions.onLoad(); assertEquals(USER_AGENT_VALUE, javascriptActions.getUserAgent()); assertEquals(DEVICE_PIXEL_RATIO_VALUE, javascriptActions.getDevicePixelRatio()); }
Example #25
Source File: StepTest.java From gaia with Mozilla Public License 2.0 | 5 votes |
@Test void fail_shouldSetEndDateTime() { var step = new Step(); step.setStartDateTime(LocalDateTime.now()); step.setEndDateTime(null); step.setExecutionTime(null); step.fail(); var timer = Duration.between(step.getStartDateTime(), step.getEndDateTime()).toMillis(); assertThat(step.getEndDateTime()).isNotNull().isEqualToIgnoringSeconds(LocalDateTime.now()); assertThat(step.getExecutionTime()).isNotNull().isEqualTo(timer); }
Example #26
Source File: CoreTest.java From camel-quarkus with Apache License 2.0 | 5 votes |
@Test void reflectiveMethod() { RestAssured.when() .get( "/test/reflection/{className}/method/{methodName}/{value}", "org.apache.commons.lang3.tuple.MutablePair", "setLeft", "Kermit") .then() .statusCode(200) .body(is("(Kermit,null)")); }
Example #27
Source File: PlatformHttpTest.java From camel-quarkus with Apache License 2.0 | 5 votes |
@Test public void customHeaderFilterStrategy() { RestAssured.given() .queryParam("k1", "v1") .queryParam("k2", "v2") .get("/platform-http/header-filter-strategy") .then() .statusCode(200) .body(equalTo("k1=\nk2=v2")); // k1 filtered out by TestHeaderFilterStrategy }
Example #28
Source File: ImageWithSourcePartFilterTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void testFilterWrongSrcPartValue() { when(webElement.getAttribute(SRC_ATTRIBUTE)).thenReturn(SRC_VALUE); List<WebElement> foundElements = search.filter(webElements, "wrongValue"); assertTrue(foundElements.isEmpty()); }
Example #29
Source File: AsyncApiContentValidatorTest.java From apicurio-registry with Apache License 2.0 | 5 votes |
@Test public void testInvalidSyntax() throws Exception { ContentHandle content = resourceToContentHandle("asyncapi-invalid-syntax.json"); AsyncApiContentValidator validator = new AsyncApiContentValidator(); Assertions.assertThrows(InvalidContentException.class, () -> { validator.validate(ValidityLevel.SYNTAX_ONLY, content); }); }
Example #30
Source File: RepositoryIT.java From sdn-rx with Apache License 2.0 | 5 votes |
@Test void findByAfter(@Autowired PersonRepository repository) { List<PersonWithAllConstructor> persons = repository.findAllByBornOnAfter(TEST_PERSON1_BORN_ON); assertThat(persons) .hasSize(1) .contains(person2); }