类org.junit.jupiter.api.Test源码实例Demo

下面列出了怎么用org.junit.jupiter.api.Test的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: chart-fx   文件: CacheTests.java
@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));
}
 
源代码2 项目: incubator-tuweni   文件: ByteBufferWriterTest.java
@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));
}
 
源代码3 项目: chart-fx   文件: DragResizerUtilTests.java
@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());
}
 
@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());

}
 
源代码5 项目: smithy   文件: BuildParameterBuilderTest.java
@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());
}
 
源代码6 项目: vividus   文件: ExpressionAdapterTests.java
@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);
}
 
源代码7 项目: kogito-runtimes   文件: NestedAccessorsTest.java
@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();
}
 
源代码8 项目: java-katas   文件: TestKata2LambdasDeeperDive.java
@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");
}
 
源代码9 项目: vividus   文件: AshotFactoryTests.java
@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);
}
 
源代码10 项目: incubator-tuweni   文件: CommonBytesTests.java
@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);
}
 
源代码11 项目: camel-quarkus   文件: CoreTest.java
@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)"));
}
 
源代码12 项目: kogito-runtimes   文件: SubProcessTest.java
@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());
}
 
源代码13 项目: mongo-kafka   文件: MongoSinkTaskTest.java
@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");
}
 
源代码14 项目: XS2A-Sandbox   文件: TppExceptionAdvisorTest.java
@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);
}
 
源代码15 项目: microservice-istio   文件: PollingTest.java
@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)));
	}
}
 
@Test
void testAfterNavigateForwardAcceptAlert()
{
    pageLoadListenerForAlertHanding.setAlertHandlingOptions(AlertHandlingOptions.ACCEPT);
    pageLoadListenerForAlertHanding.afterNavigateForward(webDriver);
    verify((JavascriptExecutor) webDriver).executeScript(ALERT_SCRIPT, true);
}
 
@Test
public void testHelloEndpoint() {
    given()
      .when().get("/getContainerId")
      .then()
         .statusCode(200);
}
 
源代码18 项目: mongo-kafka   文件: ValidatorWithOperatorsTest.java
@Test
@DisplayName("validate regex")
void simpleRegex() {
  ValidatorWithOperators validator = Validators.matching(Pattern.compile("fo+ba[rz]"));
  validator.ensureValid(NAME, "foobar");
  validator.ensureValid(NAME, "foobaz");
}
 
源代码19 项目: java-microservices-examples   文件: UserMapperIT.java
@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);
}
 
@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);
}
 
源代码21 项目: yosegi   文件: TestNullObj.java
@Test
public void T_getFloat_throwsException() throws IOException {
  PrimitiveObject obj = NullObj.getInstance();
  assertThrows( NumberFormatException.class ,
    () -> {
      obj.getFloat();
    }
  );
}
 
@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);
    });
}
 
@Test
void updateAspspConsentData_exception() throws IOException {
    // Given
    when(tokenStorageService.toBase64String(any())).thenThrow(IOException.class);

    // Then
    assertThrows(AuthorizationException.class, () -> service.updateAspspConsentData(getExpectedWorkflow("RJCT", "RJCT")));
}
 
源代码24 项目: incubator-tuweni   文件: NodeStatsTest.java
@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));
}
 
源代码25 项目: vividus   文件: PageStepsTests.java
@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);
}
 
@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);
}
 
源代码27 项目: Box   文件: TestArrayTypes.java
@Test
public void testNoDebug() {
	noDebugInfo();
	ClassNode cls = getClassNode(TestCls.class);
	String code = cls.getCode().toString();

	assertThat(code, containsOne("use(new Object[]{exc});"));
}
 
源代码28 项目: metrics   文件: BasicTimerAggregatorTest.java
@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.
}
 
源代码29 项目: gaia   文件: StepTest.java
@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);
}
 
源代码30 项目: hyena   文件: TestPointExpireStrategy.java
@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);
}
 
 类所在包
 同包方法