org.assertj.core.api.Assertions类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(11.5k)|赞(0)|评价(0)|浏览(644)

本文整理了Java中org.assertj.core.api.Assertions类的一些代码示例,展示了Assertions类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Assertions类的具体详情如下:
包路径:org.assertj.core.api.Assertions
类名称:Assertions

Assertions介绍

[英]Entry point for assertion methods for different types. Each method in this class is a static factory for a type-specific assertion object.

For example:

int removed = employees.removeFired(); 
Assertions#assertThat(int)(removed). 
IntegerAssert#isZero(); 
List<Employee> newEmployees = employees.hired(TODAY); 
Assertions#assertThat(Iterable)(newEmployees). 
IterableAssert#hasSize(int)(6);

This class only contains all assertThat methods, if you have ambiguous method compilation error, use either AssertionsForClassTypes or AssertionsForInterfaceTypesand if you need both, fully qualify you assertThat method.

Java 8 is picky when choosing the right assertThat method if the object under test is generic and bounded, for example if foo is instance of T that extends Exception, java 8 will complain that it can't resolve the proper assertThat method (normally assertThat(Throwable) as foo might implement an interface like List, if that occurred assertThat(List) would also be a possible choice - thus confusing java 8.

This why Assertions have been split in AssertionsForClassTypes and AssertionsForInterfaceTypes(see http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why).
[中]不同类型的断言方法的入口点。此类中的每个方法都是特定于类型的断言对象的静态工厂。
例如:

int removed = employees.removeFired(); 
Assertions#assertThat(int)(removed). 
IntegerAssert#isZero(); 
List<Employee> newEmployees = employees.hired(TODAY); 
Assertions#assertThat(Iterable)(newEmployees). 
IterableAssert#hasSize(int)(6);

该类仅包含所有assertThat方法,如果存在不明确的方法编译错误,请使用AssertionsForClassTypes或AssertionsForInterfaceTypes,如果两者都需要,请完全限定assertThat方法。
如果测试对象是泛型且有界的,Java 8在选择正确的assertThat方法时很挑剔,例如,如果foo是扩展Exception的T的实例,java 8会抱怨它无法解析正确的assertThat方法(通常是assertThat(Throwable),因为foo可能会实现类似列表的接口,如果出现这种情况,assertThat(List)也可能是一个可能的选择-从而混淆java 8。
这就是为什么断言被划分为类类型断言和接口类型断言(参见http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why).

代码示例

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testSimpleLong() throws Exception {
 String[] args = new String[]{"--enable-a",
   "--bfile", "toast",
   "foo", "bar"};
 CommandLine evaluated = cli.parse(Arrays.asList(args));
 assertThat(getBooleanOption(evaluated, "a")).isTrue();
 assertThat(getStringOption(evaluated, "b")).isEqualTo("toast");
 assertThat(getStringOption(evaluated, "bfile")).isEqualTo("toast");
 assertThat(getBooleanOption(evaluated, "c")).isFalse();
 assertThat(evaluated.allArguments()).contains("foo", "bar").hasSize(2);
}

代码示例来源:origin: prestodb/presto

@Test(groups = CLI, timeOut = TIMEOUT)
public void shouldExitOnErrorFromExecute()
    throws IOException, InterruptedException
{
  String sql = "select * from hive.default.nations; select * from hive.default.nation;";
  launchPrestoCliWithServerArgument("--execute", sql);
  assertThat(trimLines(presto.readRemainingOutputLines())).isEmpty();
  assertThatThrownBy(() -> presto.waitForWithTimeoutAndKill()).hasMessage("Child process exited with non-zero code: 1");
}

代码示例来源:origin: prestodb/presto

private void waitForNodeRefresh()
    throws InterruptedException
{
  long deadline = System.currentTimeMillis() + MINUTES.toMillis(1);
  while (System.currentTimeMillis() < deadline) {
    if (getActiveNodesUrls().size() == 3) {
      return;
    }
    Thread.sleep(100);
  }
  fail("Worker nodes haven't been discovered in 1 minutes.");
}

代码示例来源:origin: prestodb/presto

@Test(groups = CLI, timeOut = TIMEOUT)
public void shouldNotExitOnErrorFromExecute()
    throws IOException, InterruptedException
{
  String sql = "select * from hive.default.nations; select * from hive.default.nation;";
  launchPrestoCliWithServerArgument("--execute", sql, "--ignore-errors");
  assertThat(trimLines(presto.readRemainingOutputLines())).containsAll(nationTableBatchLines);
  assertThatThrownBy(() -> presto.waitForWithTimeoutAndKill()).hasMessage("Child process exited with non-zero code: 1");
}

代码示例来源:origin: springside/springside4

@Test
public void stringAndInt() {
  assertThat(IPUtil.ipv4StringToInt("192.168.0.1")).isEqualTo(-1062731775);
  assertThat(IPUtil.ipv4StringToInt("192.168.0.2")).isEqualTo(-1062731774);
  assertThat(IPUtil.intToIpv4String(-1062731775)).isEqualTo("192.168.0.1");
  assertThat(IPUtil.intToIpv4String(-1062731774)).isEqualTo("192.168.0.2");
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void required_param() {
 underTest.setParam("a_required_string", "foo");
 underTest.setParam("a_required_number", "42");
 underTest.setParam("a_required_boolean", "true");
 underTest.setParam("a_required_enum", "BETA");
 assertThat(underTest.mandatoryParam("a_required_string")).isEqualTo("foo");
 assertThat(underTest.mandatoryParamAsBoolean("a_required_boolean")).isTrue();
 assertThat(underTest.mandatoryParamAsInt("a_required_number")).isEqualTo(42);
 assertThat(underTest.mandatoryParamAsLong("a_required_number")).isEqualTo(42L);
 assertThat(underTest.mandatoryParamAsEnum("a_required_enum", RuleStatus.class)).isEqualTo(RuleStatus.BETA);
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void overridden_rule() {
 List<Rule> rules = parseAnnotatedClass(OverridingRule.class);
 assertThat(rules).hasSize(1);
 Rule rule = rules.get(0);
 assertThat(rule.getKey()).isEqualTo("overriding_foo");
 assertThat(rule.getName()).isEqualTo("Overriding Foo");
 assertThat(rule.getDescription()).isNull();
 assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR);
 assertThat(rule.getParams()).hasSize(2);
}

代码示例来源:origin: springside/springside4

@Test
public void pairTest() {
  Pair<String, Integer> pair = Pair.of("haha", 1);
  Pair<String, Integer> pair2 = Pair.of("haha", 2);
  Pair<String, Integer> pair3 = Pair.of("kaka", 1);
  assertThat(pair.equals(pair2)).isFalse();
  assertThat(pair.equals(pair3)).isFalse();
  assertThat(pair.hashCode() != pair2.hashCode()).isTrue();
  assertThat(pair.toString()).isEqualTo("Pair [left=haha, right=1]");

  assertThat(pair.getLeft()).isEqualTo("haha");
  assertThat(pair.getRight()).isEqualTo(1);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnTheCorrectName() {
  Retry retry = retryRegistry.retry("testName");
  Assertions.assertThat(retry).isNotNull();
  Assertions.assertThat(retry.getName()).isEqualTo("testName");
}

代码示例来源:origin: prestodb/presto

@Test(groups = {LDAP, LDAP_CLI, PROFILE_SPECIFIC_TESTS}, timeOut = TIMEOUT)
public void shouldFailQueryForEmptyUser()
    throws IOException
{
  ldapUserName = "";
  launchPrestoCliWithServerArgument("--execute", "select * from hive.default.nation;");
  assertThat(trimLines(presto.readRemainingErrorLines())).anySatisfy(line ->
      assertThat(line).contains("Malformed decoded credentials"));
}

代码示例来源:origin: springside/springside4

@Test
public void general() {
  List<String> list1 = ListUtil.newArrayList();
  List<String> list2 = ListUtil.newArrayList("a", "b", "c");
  List<String> list3 = ListUtil.newArrayList("a");
  assertThat(ListUtil.isEmpty(list1)).isTrue();
  assertThat(ListUtil.isEmpty(null)).isTrue();
  assertThat(ListUtil.isEmpty(list2)).isFalse();
  assertThat(ListUtil.isNotEmpty(list1)).isFalse();
  assertThat(ListUtil.isNotEmpty(null)).isFalse();
  assertThat(ListUtil.isNotEmpty(list2)).isTrue();
  assertThat(ListUtil.getFirst(list2)).isEqualTo("a");
  assertThat(ListUtil.getLast(list2)).isEqualTo("c");
  assertThat(ListUtil.getFirst(list3)).isEqualTo("a");
  assertThat(ListUtil.getLast(list3)).isEqualTo("a");
  assertThat(ListUtil.getFirst(list1)).isNull();
  assertThat(ListUtil.getFirst(null)).isNull();
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void verify_mapping_from_dto() {
 for (Metric.MetricType metricType : Metric.MetricType.values()) {
  MetricDto metricDto = createMetricDto(metricType);
  Metric metric = underTest.apply(metricDto);
  assertThat(metric.getId()).isEqualTo(metricDto.getId());
  assertThat(metric.getKey()).isEqualTo(metricDto.getKey());
  assertThat(metric.getName()).isEqualTo(metricDto.getShortName());
  assertThat(metric.getType()).isEqualTo(metricType);
  assertThat(metric.isBestValueOptimized()).isFalse();
  assertThat(metric.getBestValue()).isEqualTo(SOME_BEST_VALUE);
 }
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void testInvokeToString() throws Throwable {
  final Method toStringMethod = testService.getClass().getMethod("toString");
  final Object result = testSubject.invoke(testService, toStringMethod, new Object[0]);
  verify(methodHandler, times(0)).invoke(any());
  assertThat(feignDecorator.isCalled())
      .describedAs("FeignDecorator is called")
      .isTrue();
  assertThat(result)
      .describedAs("Return of invocation")
      .isEqualTo(target.toString());
}

代码示例来源:origin: evernote/android-job

private void verifyJob(long wait, TimeUnit timeUnit) throws InterruptedException {
    assertThat(mJob.mLatch.await(wait, timeUnit)).isTrue();
    Bundle extras = mParams.getTransientExtras();
    assertThat(extras).isNotNull();
    assertThat(extras.getString("Key")).isEqualTo("Value");
  }
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void api_definition() {
 WebService.Action definition = ws.getDef();
 assertThat(definition.since()).isEqualTo("6.1");
 assertThat(definition.isPost()).isTrue();
 assertThat(definition.key()).isEqualTo("update_key");
 assertThat(definition.changelog()).hasSize(2);
 assertThat(definition.params())
  .hasSize(3)
  .extracting(Param::key)
  .containsOnlyOnce("projectId", "from", "to");
}

代码示例来源:origin: twosigma/beakerx

@Test
public void setyAutoRangeByTrue_YAutoRangeIsTrue() {
 //given
 AbstractChart chart =createWidget();
 //when
 chart.setyAutoRange(true);
 //then
 assertThat(chart.getYAutoRange()).isTrue();
 LinkedHashMap model = getModelUpdate();
 assertThat(model.size()).isEqualTo(1);
 assertThat(model.get(Y_AUTO_RANGE)).isEqualTo(true);
}

代码示例来源:origin: twosigma/beakerx

@Test
public void setyLabel_hasYLabel() {
 //given
 AbstractChart chart =createWidget();
 //when
 chart.setyLabel("test_y");
 //then
 assertThat(chart.getYLabel()).isEqualTo("test_y");
 LinkedHashMap model = getModelUpdate();
 assertThat(model.size()).isEqualTo(1);
 assertThat(model.get(Y_LABEL)).isEqualTo("test_y");
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void check_component_keys() {
 db.prepareDbUnit(getClass(), "shared.xml");
 Map<String, Boolean> result = underTest.checkComponentKeys(dbSession, newArrayList("foo:struts", "foo:struts-core", "foo:struts-ui"));
 assertThat(result)
  .hasSize(3)
  .containsOnly(entry("foo:struts", false), entry("foo:struts-core", true), entry("foo:struts-ui", false));
}

代码示例来源:origin: springside/springside4

@Test
public void copySingleObject() {
  Student student = new Student("zhang3", 20, new Teacher("li4"), ListUtil.newArrayList("chinese", "english"));
  StudentVO studentVo = BeanMapper.map(student, StudentVO.class);
  assertThat(studentVo.name).isEqualTo("zhang3");
  assertThat(studentVo.getAge()).isEqualTo(20);
  assertThat(studentVo.getTeacher().getName()).isEqualTo("li4");
  assertThat(studentVo.getCourse()).containsExactly("chinese", "english");
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testWithANonMatchingFile() throws IOException, InterruptedException {
 watcher.watch();
 // Initial deployment
 assertWaitUntil(() -> deploy.get() == 1);
 File file = new File(root, "foo.nope");
 file.createNewFile();
 Thread.sleep(500);
 assertThat(undeploy.get()).isEqualTo(0);
 assertThat(deploy.get()).isEqualTo(1);
}

相关文章