Java Code Examples for org.junit.jupiter.api.Test
The following examples show how to use
org.junit.jupiter.api.Test. 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: chart-fx Source File: CacheTests.java License: 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 2
Source Project: incubator-tuweni Source File: ByteBufferWriterTest.java License: 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 3
Source Project: chart-fx Source File: DragResizerUtilTests.java License: 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 4
Source Project: quaerite Source File: TestParameterizableStringListFactory.java License: 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 Project: smithy Source File: BuildParameterBuilderTest.java License: 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 6
Source Project: vividus Source File: ExpressionAdapterTests.java License: 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 7
Source Project: kogito-runtimes Source File: NestedAccessorsTest.java License: 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 8
Source Project: java-katas Source File: TestKata2LambdasDeeperDive.java License: 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 9
Source Project: vividus Source File: AshotFactoryTests.java License: 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 10
Source Project: incubator-tuweni Source File: CommonBytesTests.java License: Apache License 2.0 | 5 votes |
@Test void testUpdate() throws NoSuchAlgorithmException { // Digest the same byte array in 4 ways: // 1) directly from the array // 2) after wrapped using the update() method // 3) after wrapped and copied using the update() method // 4) after wrapped but getting the byte manually // and check all compute the same digest. MessageDigest md1 = MessageDigest.getInstance("SHA-1"); MessageDigest md2 = MessageDigest.getInstance("SHA-1"); MessageDigest md3 = MessageDigest.getInstance("SHA-1"); MessageDigest md4 = MessageDigest.getInstance("SHA-1"); byte[] toDigest = new BigInteger("12324029423415041783577517238472017314").toByteArray(); Bytes wrapped = w(toDigest); byte[] digest1 = md1.digest(toDigest); wrapped.update(md2); byte[] digest2 = md2.digest(); wrapped.copy().update(md3); byte[] digest3 = md3.digest(); for (int i = 0; i < wrapped.size(); i++) md4.update(wrapped.get(i)); byte[] digest4 = md4.digest(); assertArrayEquals(digest2, digest1); assertArrayEquals(digest3, digest1); assertArrayEquals(digest4, digest1); }
Example 11
Source Project: camel-quarkus Source File: CoreTest.java License: 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 12
Source Project: kogito-runtimes Source File: SubProcessTest.java License: Apache License 2.0 | 5 votes |
@Test public void testNonExistentSubProcess() { String nonExistentSubProcessName = "nonexistent.process"; RuleFlowProcess process = new RuleFlowProcess(); process.setId("org.drools.core.process.process"); process.setName("Process"); StartNode startNode = new StartNode(); startNode.setName("Start"); startNode.setId(1); SubProcessNode subProcessNode = new SubProcessNode(); subProcessNode.setName("SubProcessNode"); subProcessNode.setId(2); subProcessNode.setProcessId(nonExistentSubProcessName); EndNode endNode = new EndNode(); endNode.setName("End"); endNode.setId(3); connect(startNode, subProcessNode); connect(subProcessNode, endNode); process.addNode( startNode ); process.addNode( subProcessNode ); process.addNode( endNode ); KieSession ksession = createKieSession(process); ProcessInstance pi = ksession.startProcess("org.drools.core.process.process"); assertEquals(ProcessInstance.STATE_ERROR, pi.getState()); }
Example 13
Source Project: mongo-kafka Source File: MongoSinkTaskTest.java License: Apache License 2.0 | 5 votes |
@Test @DisplayName("test with default config and no sink records") void testBuildWriteModelDefaultConfigSinkRecordsAbsent() { List<? extends WriteModel> writeModelList = new MongoSinkTask().buildWriteModel(createTopicConfig(), emptyList()); assertNotNull(writeModelList, "WriteModel list was null"); assertEquals(emptyList(), writeModelList, "WriteModel list mismatch"); }
Example 14
Source Project: XS2A-Sandbox Source File: TppExceptionAdvisorTest.java License: Apache License 2.0 | 5 votes |
@Test void handleFeignException() throws NoSuchMethodException, JsonProcessingException, NoSuchFieldException { // Given FieldSetter.setField(service, service.getClass().getDeclaredField("objectMapper"), STATIC_MAPPER); // When ResponseEntity<Map> result = service.handleFeignException(FeignException.errorStatus("method", getResponse()), new HandlerMethod(service, "toString", null)); ResponseEntity<Map<String, String>> expected = ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(getExpected(401, "status 401 reading method")); // Then compareBodies(result, expected); }
Example 15
Source Project: microservice-istio Source File: PollingTest.java License: Apache License 2.0 | 5 votes |
@Test public void orderArePolled() { long countBeforePoll = bonusRepository.count(); bonusPoller.pollInternal(); assertThat(bonusRepository.count(), is(greaterThan(countBeforePoll))); for (Bonus bonus : bonusRepository.findAll()) { assertThat(bonus.getRevenue(), is(greaterThan(0.0))); } }
Example 16
Source Project: vividus Source File: AlertHandlingPageLoadListenerTests.java License: Apache License 2.0 | 5 votes |
@Test void testAfterNavigateForwardAcceptAlert() { pageLoadListenerForAlertHanding.setAlertHandlingOptions(AlertHandlingOptions.ACCEPT); pageLoadListenerForAlertHanding.afterNavigateForward(webDriver); verify((JavascriptExecutor) webDriver).executeScript(ALERT_SCRIPT, true); }
Example 17
Source Project: Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus Source File: HelloOKDTest.java License: MIT License | 5 votes |
@Test public void testHelloEndpoint() { given() .when().get("/getContainerId") .then() .statusCode(200); }
Example 18
Source Project: mongo-kafka Source File: ValidatorWithOperatorsTest.java License: Apache License 2.0 | 5 votes |
@Test @DisplayName("validate regex") void simpleRegex() { ValidatorWithOperators validator = Validators.matching(Pattern.compile("fo+ba[rz]")); validator.ensureValid(NAME, "foobar"); validator.ensureValid(NAME, "foobaz"); }
Example 19
Source Project: java-microservices-examples Source File: UserMapperIT.java License: Apache License 2.0 | 5 votes |
@Test public void usersToUserDTOsShouldMapOnlyNonNullUsers() { List<User> users = new ArrayList<>(); users.add(user); users.add(null); List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users); assertThat(userDTOS).isNotEmpty(); assertThat(userDTOS).size().isEqualTo(1); }
Example 20
Source Project: vividus Source File: StringToListSequenceActionConverterTests.java License: Apache License 2.0 | 5 votes |
@Test void testConvertKeys() { String value = "|type |argument |\n" + "|PRESS_KEYS|value1,value2|"; List<SequenceAction> actions = converter.convertValue(value, null); assertThat(actions, hasSize(1)); verifySequenceAction(actions.get(0), SequenceActionType.PRESS_KEYS, List.of("value1", "value2")); verifyNoMoreInteractions(stringToSearchAttributesConverter, pointConverter); }
Example 21
Source Project: yosegi Source File: TestNullObj.java License: Apache License 2.0 | 5 votes |
@Test public void T_getFloat_throwsException() throws IOException { PrimitiveObject obj = NullObj.getInstance(); assertThrows( NumberFormatException.class , () -> { obj.getFloat(); } ); }
Example 22
Source Project: smallrye-graphql Source File: AuthorizationHeaderBehavior.java License: Apache License 2.0 | 5 votes |
@Test public void shouldAddPlainTokenAuthorizationHeader() { withToken("", () -> { fixture.returnsData("'plainGreeting':'dummy-greeting'"); TokenAuthorizationHeadersApi api = fixture.builder().build(TokenAuthorizationHeadersApi.class); api.plainGreeting(); then(fixture.sentHeader("Authorization")).isEqualTo(BEARER_AUTH); }); }
Example 23
Source Project: XS2A-Sandbox Source File: CommonPaymentServiceImplTest.java License: Apache License 2.0 | 5 votes |
@Test void updateAspspConsentData_exception() throws IOException { // Given when(tokenStorageService.toBase64String(any())).thenThrow(IOException.class); // Then assertThrows(AuthorizationException.class, () -> service.updateAspspConsentData(getExpectedWorkflow("RJCT", "RJCT"))); }
Example 24
Source Project: incubator-tuweni Source File: NodeStatsTest.java License: Apache License 2.0 | 5 votes |
@Test void toJson() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new EthJsonModule()); NodeStats stats = new NodeStats(true, true, true, 42, 23, 5000, 1234567); assertEquals( "{\"active\":true,\"syncing\":true,\"mining\":true,\"hashrate\":42,\"peers\":23,\"gasPrice\":5000,\"uptime\":1234567}", mapper.writeValueAsString(stats)); }
Example 25
Source Project: vividus Source File: PageStepsTests.java License: Apache License 2.0 | 5 votes |
@Test void testCheckUriIsLoaded() { String url = HTTP_EXAMPLE_COM; when(webDriverProvider.get()).thenReturn(driver); when(driver.getCurrentUrl()).thenReturn(url); pageSteps.checkUriIsLoaded(url); verify(softAssert).assertEquals("Page has correct URL", url, url); }
Example 26
Source Project: java-microservices-examples Source File: HibernateTimeZoneIT.java License: Apache License 2.0 | 5 votes |
@Test @Transactional public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper .getOffsetDateTime() .format(dateTimeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); }
Example 27
Source Project: Box Source File: TestArrayTypes.java License: Apache License 2.0 | 5 votes |
@Test public void testNoDebug() { noDebugInfo(); ClassNode cls = getClassNode(TestCls.class); String code = cls.getCode().toString(); assertThat(code, containsOne("use(new Object[]{exc});")); }
Example 28
Source Project: metrics Source File: BasicTimerAggregatorTest.java License: Apache License 2.0 | 5 votes |
@Test public void testGrowTableWithMaxCapacity() { final BasicTimerAggregator aggregator = new BasicTimerAggregator("test", 3, 1); aggregator.apply(new String[]{}, 1L, CURRENT_TIME); aggregator.apply(new String[]{"testTag", "value"}, 1L, CURRENT_TIME); aggregator.apply(new String[]{"testTag", "value2"}, 1L, CURRENT_TIME); // Silently ignored, over capacity aggregator.apply(new String[]{"testTag", "value3"}, 1L, CURRENT_TIME); assertEquals(3, aggregator.size()); assertEquals(3, aggregator.capacity()); // caped at the max capacity. }
Example 29
Source Project: gaia Source File: StepTest.java License: 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 30
Source Project: hyena Source File: TestPointExpireStrategy.java License: 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); }