The juneau-assertions module in Juneau is a powerful API for performing fluent style assertions.
Fluent assertions have two types of methods:
- "asX" methods which perform transformations.
- "isX" methods which perform assertions.
Multiple transformations and assertions can be performed per statement.
| import static org.apache.juneau.assertions.Assertions.*;
| import static org.apache.juneau.assertions.AssertionPredicates.*;
|
| // Check the contents of a string.
| assertString("foo, bar")
| .asSplit(",")
| .asTrimmed()
| .is("foo", "bar");
|
| // Extract a subset of properties from a list of beans and compare using Simplified JSON.
| List<MyBean> myListOfBeans = ...;
| assertBeanList(myListOfBeans)
| .asPropertyMaps("a,b")
| .asJson().is("[{a:1,b:'foo'}]");
|
| // Perform an arbitrary Predicate check against a bean.
| MyBean myBean = ...;
| assertBean(myBean)
| .is(x -> isValidCheck(x))
|
| // Check that a list of strings has less than 10 entries and the first
| // 3 entries are [foo, bar*, null] using assertion predicates.
| List<String> myListOfStrings = ...;
| assertStringList(myListOfStrings)
| .asSize().isLt(10)
| .asFirst(3)
| .is(eq("foo"),match("bar*"),isNull())
|
| // Check that an exception is thrown and is the specified type and has the specified message.
| assertThrown(()->myBean.runBadMethod())
| .isExists()
| .isExactType(RuntimeException.class)
| .asMessage().is("foo");
The Assertions APIs are used throughout the REST client and server APIs for performing inline assertions on REST requests and responses.
| // Create a basic REST client with JSON support and download a bean.
| MyBean bean = RestClient.create()
| .json5()
| .build()
| .get(URI)
| .run()
| .assertStatus().asCode().is(200)
| .assertHeader("Content-Type").isMatches("application/json*")
| .getContent().assertValue().asString().isContains("OK")
| .getContent().as(MyBean.class);