org.assertj.core.api.AbstractIterableAssert.extracting()方法的使用及代码示例

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

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

AbstractIterableAssert.extracting介绍

[英]Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.

It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which can be be much less work !

Let's take a look at an example to make things clearer :

// build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class) 
// they can be public field or properties, both can be extracted. 
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>(); 
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA)); 
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF)); 
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF)); 
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN); 
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN)); 
// let's verify the names of the TolkienCharacters in fellowshipOfTheRing : 
assertThat(fellowshipOfTheRing).extracting("name") 
.contains("Boromir", "Gandalf", "Frodo") 
.doesNotContain("Sauron", "Elrond"); 
// you can extract nested properties/fields like the name of the race : 
assertThat(fellowshipOfTheRing).extracting("race.name") 
.contains("Hobbit", "Elf") 
.doesNotContain("Orc");

A property with the given name is searched for first. If it doesn't exist a field with the given name is looked for. If the field does not exist an IntrospectionError is thrown. By default private fields are read but you can change this with Assertions#setAllowComparingPrivateFields(boolean). Trying to read a private field when it's not allowed leads to an IntrospectionError.

Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values order.

Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values corresponding to the given keys.

Example:

Employee yoda = new Employee(1L, new Name("Yoda"), 800); 
Employee luke = new Employee(2L, new Name("Luke"), 22); 
Employee han = new Employee(3L, new Name("Han"), 31); 
// build two maps 
Map<String, Employee> map1 = new HashMap<>(); 
map1.put("key1", yoda); 
map1.put("key2", luke); 
Map<String, Employee> map2 = new HashMap<>(); 
map2.put("key1", yoda); 
map2.put("key2", han); 
// instead of a list of objects, we have a list of maps 
List<Map<String, Employee>> maps = asList(map1, map2); 
// extracting a property in that case = get values from maps using the property as a key 
assertThat(maps).extracting("key2").containsExactly(luke, han); 
assertThat(maps).extracting("key1").containsExactly(yoda, yoda); 
// type safe version 
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han); 
// it works with several keys, extracted values being wrapped in a Tuple 
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han)); 
// unknown keys leads to null (map behavior) 
assertThat(maps).extracting("bad key").containsExactly(null, null);

[中]将给定字段或属性的值从受测Iterable的元素中提取到新Iterable中,此新Iterable将成为受测Iterable。
它允许您测试Iterable元素的属性/字段,而不是测试元素本身,这可能需要更少的工作!
让我们看一个例子让事情更清楚:

// build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class) 
// they can be public field or properties, both can be extracted. 
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>(); 
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA)); 
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF)); 
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT)); 
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF)); 
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN); 
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN)); 
// let's verify the names of the TolkienCharacters in fellowshipOfTheRing : 
assertThat(fellowshipOfTheRing).extracting("name") 
.contains("Boromir", "Gandalf", "Frodo") 
.doesNotContain("Sauron", "Elrond"); 
// you can extract nested properties/fields like the name of the race : 
assertThat(fellowshipOfTheRing).extracting("race.name") 
.contains("Hobbit", "Elf") 
.doesNotContain("Orc");

首先搜索具有给定名称的属性。如果不存在,将查找具有给定名称的字段。如果该字段不存在,则抛出内省错误。默认情况下,将读取私有字段,但您可以使用断言#setAllowComparingPrivateFields(布尔值)更改此设置。在不允许的情况下尝试读取私有字段会导致内省错误。
请注意,提取的属性/字段值的顺序与被测Iterable的迭代顺序一致,例如,如果它是哈希集,则无法对提取的值顺序进行任何假设。
提取还支持贴图,即,它不从对象中提取值,而是提取与给定关键帧对应的贴图值。
例子:

Employee yoda = new Employee(1L, new Name("Yoda"), 800); 
Employee luke = new Employee(2L, new Name("Luke"), 22); 
Employee han = new Employee(3L, new Name("Han"), 31); 
// build two maps 
Map<String, Employee> map1 = new HashMap<>(); 
map1.put("key1", yoda); 
map1.put("key2", luke); 
Map<String, Employee> map2 = new HashMap<>(); 
map2.put("key1", yoda); 
map2.put("key2", han); 
// instead of a list of objects, we have a list of maps 
List<Map<String, Employee>> maps = asList(map1, map2); 
// extracting a property in that case = get values from maps using the property as a key 
assertThat(maps).extracting("key2").containsExactly(luke, han); 
assertThat(maps).extracting("key1").containsExactly(yoda, yoda); 
// type safe version 
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han); 
// it works with several keys, extracted values being wrapped in a Tuple 
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han)); 
// unknown keys leads to null (map behavior) 
assertThat(maps).extracting("bad key").containsExactly(null, null);

代码示例

代码示例来源:origin: json-path/JsonPath

@Test
public void list_of_numbers() {
  JsonArray objs =  using(GSON_CONFIGURATION).parse(JSON_DOCUMENT).read("$.store.book[*].display-price");
  assertThat(objs.iterator()).extracting("asDouble").containsExactly(8.95D, 12.99D, 8.99D, 22.99D);
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void should_not_mix_indexes_from_different_tables() {
 String[] statements = {
  "CREATE TABLE test_ab (a int PRIMARY KEY, b int);",
  "CREATE INDEX test_b on test_ab (b);",
  "CREATE TABLE test_cd (c int PRIMARY KEY, d int);",
  "CREATE INDEX test_d on test_cd (d);",
 };
 for (String statement : statements) session().execute(statement);
 TableMetadata table_ab = cluster().getMetadata().getKeyspace(keyspace).getTable("test_ab");
 TableMetadata table_cd = cluster().getMetadata().getKeyspace(keyspace).getTable("test_cd");
 assertThat(table_ab.getIndexes().size()).isEqualTo(1);
 assertThat(table_ab.getIndexes()).extracting("name").containsOnly("test_b");
 assertThat(table_cd.getIndexes().size()).isEqualTo(1);
 assertThat(table_cd.getIndexes()).extracting("name").containsOnly("test_d");
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

.extracting(
  new Extractor<Thread, String>() {
   @Override

代码示例来源:origin: org.assertj/assertj-core-java8

return extracting(byName(propertiesOrFields));

代码示例来源:origin: allegro/hermes

private ListAssert<String> assertThatSubscriptionIsAssignedTo(SubscriptionAssignmentView work, SubscriptionName sub, List<String> nodeIds) {
    return assertThat(work.getAssignmentsForSubscription(sub))
        .extracting(SubscriptionAssignment::getConsumerNodeId).containsOnly(nodeIds.stream().toArray(String[]::new));
  }
}

代码示例来源:origin: SonarSource/sonar-php

/**
 * Checks that the specified symbol references match with the symbol references of the specified symbol.
 * @param line the line of the symbol
 * @param column any column of the symbol
 * @param referenceRanges all references to the symbol
 */
public void checkSymbolReferences(SensorContextTester context, int line, int column, List<? extends TextRange> referenceRanges) {
 Collection<TextRange> foundReferences = context.referencesForSymbolAt(componentKey, line, column);
 String message = "number of found references to the symbol located at line " + line + " and column " + column;
 assertThat(foundReferences.size()).as(message).isEqualTo(referenceRanges.size());
 for (TextRange referenceRange : referenceRanges) {
  assertThat(foundReferences).extracting("start", "end").contains(tuple(referenceRange.start(), referenceRange.end()));
 }
}

代码示例来源:origin: com.datastax.dse/dse-java-driver-core

@SuppressWarnings("unchecked")
 public <T> VertexAssert hasProperty(String propertyName, T value, Class<T> clazz) {
  hasProperty(propertyName);
  assertThat(actual.getProperties(propertyName))
    .extracting(GraphExtractors.vertexPropertyValueAs(clazz))
    .contains(value);
  return myself;
 }
}

代码示例来源:origin: jerrinot/subzero

@Test
  public void useForClasses() {
    Config config = new Config();
    SubZero.useForClasses(config, String.class);

    Collection<SerializerConfig> serializerConfigs = config.getSerializationConfig().getSerializerConfigs();
    assertThat(serializerConfigs)
        .extracting("typeClass")
        .contains(String.class);
  }
}

代码示例来源:origin: com.datastax.dse/dse-java-driver-core

@SuppressWarnings("unchecked")
 public <T> S hasProperty(String propertyName, T value, Class<T> clazz) {
  hasProperty(propertyName);
  assertThat(actual.getProperties(propertyName))
    .extracting(propertyValueAs(clazz))
    .contains(value);
  return myself;
 }
}

代码示例来源:origin: com.datastax.dse/dse-java-driver-core

@Test(groups = "short")
public void should_not_mix_indexes_from_different_tables() {
 String[] statements = {
  "CREATE TABLE test_ab (a int PRIMARY KEY, b int);",
  "CREATE INDEX test_b on test_ab (b);",
  "CREATE TABLE test_cd (c int PRIMARY KEY, d int);",
  "CREATE INDEX test_d on test_cd (d);",
 };
 for (String statement : statements) session().execute(statement);
 TableMetadata table_ab = cluster().getMetadata().getKeyspace(keyspace).getTable("test_ab");
 TableMetadata table_cd = cluster().getMetadata().getKeyspace(keyspace).getTable("test_cd");
 assertThat(table_ab.getIndexes().size()).isEqualTo(1);
 assertThat(table_ab.getIndexes()).extracting("name").containsOnly("test_b");
 assertThat(table_cd.getIndexes().size()).isEqualTo(1);
 assertThat(table_cd.getIndexes()).extracting("name").containsOnly("test_d");
}

代码示例来源:origin: SonarSource/sonar-php

@Test
public void read_symbols() {
 String body = "" +
  "$foo = 1;" +
  "$bar = bar();" +
  "$bar += bar();" +
  "read($bar);" +
  "$qix += 1 + 2;";
 CompilationUnitTree cut = parse("<?php function f() { " + body + " }", PHPLexicalGrammar.COMPILATION_UNIT);
 SymbolTableImpl symbolTable = SymbolTableImpl.create(cut);
 FunctionDeclarationTree functionTree = (FunctionDeclarationTree) cut.script().statements().get(0);
 ControlFlowGraph cfg = ControlFlowGraph.build(functionTree.body());
 LiveVariablesAnalysis analysis = LiveVariablesAnalysis.analyze(cfg, symbolTable);
 Set<Symbol> readSymbols = analysis.getReadSymbols();
 assertThat(readSymbols).extracting("name").containsExactlyInAnyOrder("$bar", "$qix");
}

代码示例来源:origin: com.datastax.dse/dse-java-driver-core

.extracting(
  new Extractor<Thread, String>() {
   @Override

相关文章

微信公众号

最新文章

更多