<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Programming Languages &#8211; Zhijun Chen</title>
	<atom:link href="https://zhijunchen.com/category/programming-languages/feed/" rel="self" type="application/rss+xml" />
	<link>https://zhijunchen.com</link>
	<description></description>
	<lastBuildDate>Fri, 07 Jun 2024 06:25:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.4</generator>

<image>
	<url>https://zhijunchen.com/wp-content/uploads/2021/03/cropped-my-site-icon-1-32x32.png</url>
	<title>Programming Languages &#8211; Zhijun Chen</title>
	<link>https://zhijunchen.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Use Java Annotation With JUnit 5 Extension</title>
		<link>https://zhijunchen.com/use-java-annotation-with-junit-5-extension/</link>
		
		<dc:creator><![CDATA[Zhijun Chen]]></dc:creator>
		<pubDate>Fri, 07 Jun 2024 06:22:38 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<guid isPermaLink="false">https://zhijunchen.com/?p=222</guid>

					<description><![CDATA[Java annotations are quite useful in many areas such as introspection, Aspect-Oriented Programming, etc. Spring Framework uses quite a lot of annotations. My team has been using annotations extensively in our projects and one particular use case is using annotations together with JUnit 5 ParameterResolver to inject test resources. We will start by creating a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Java annotations are quite useful in many areas such as introspection, Aspect-Oriented Programming, etc. <a href="https://spring.io/projects/spring-framework" target="_blank" rel="noreferrer noopener">Spring Framework</a> uses quite a lot of annotations. My team has been using annotations extensively in our projects and one particular use case is using annotations together with JUnit 5 <a href="https://junit.org/junit5/docs/5.0.2/api/org/junit/jupiter/api/extension/ParameterResolver.html" target="_blank" rel="noreferrer noopener">ParameterResolver</a> to inject test resources.</p>



<p>We will start by creating a custom annotation:</p>



<pre class="wp-block-code"><code lang="java" class="language-java">@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FileResource {
  /**
   * @return the path to the resource.
   */
  String value();

  /**
   * @return the type of value that should be decoded from the resource
   */
  Class&lt;?&gt; type() default String.class;
}</code></pre>



<p>Then we would need to implement a custom ParameterResolver using the annotation.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">public class FileResourceParameterResolver implements ParameterResolver {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  @Override
  public boolean supportsParameter(ParameterContext parameterContext, 
      ExtensionContext extensionContext) throws ParameterResolutionException {
    FileResource fileResource = parameterContext
        .findAnnotation(FileResource.class).orElse(null);
    return fileResource != null &amp;&amp; 
        fileResource.type().isAssignableFrom(
        parameterContext.getParameter().getType());
  }

  @SneakyThrows
  @Override
  public Object resolveParameter(ParameterContext parameterContext, 
      ExtensionContext extensionContext) throws ParameterResolutionException {
    var fileResource = parameterContext
        .findAnnotation(FileResource.class)
        .orElseThrow(IllegalArgumentException::new);
    String path = fileResource.value();
    InputStream content = getClass().getClassLoader().getResourceAsStream(path);
    if (content == null) {
      throw new ParameterResolutionException("Resource not found: " + path);
    }
    if (fileResource.type() == String.class) {
      return IOUtils.toString(content, StandardCharsets.UTF_8);
    }
    return MAPPER.readValue(content, parameterContext.getParameter().getType());
  }
}</code></pre>



<p>Now we have our custom ParameterResolver ready to use. In our test, what we need to do is the following:</p>



<pre class="wp-block-code"><code lang="java" class="language-java">@ExtendWith({ FileResourceParameterResolver.class })
class SomeTest {

  @Test
  void importResourceTest(@FileResource("some/json/file.json") String inputJson) {
    // use content below in test
  }
}</code></pre>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java Just-In-Time(JIT) Compiler Overview</title>
		<link>https://zhijunchen.com/java-just-in-timejit-compiler-overview/</link>
		
		<dc:creator><![CDATA[Zhijun Chen]]></dc:creator>
		<pubDate>Thu, 15 Apr 2021 21:17:32 +0000</pubDate>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://zhijunchen.com/?p=143</guid>

					<description><![CDATA[The JIT compiler is the heart of the Java Virtual Machine(JVM). It improves the performance of Java applications at runtime. Nothing controls the performance of your application more than the JIT compiler. Nowadays we don&#8217;t normally need to tune the JIT compiler due to popularity of Microservices framework like Spring Boot, but in my opinion [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>The JIT compiler is the heart of the Java Virtual Machine(JVM). It improves the performance of Java applications at runtime. Nothing controls the performance of your application more than the JIT compiler.</p>



<p>Nowadays we don&#8217;t normally need to tune the JIT compiler due to popularity of Microservices framework like <a href="https://spring.io/projects/spring-boot">Spring Boot</a>, but in my opinion it is still good to know how things work under the hood. The following picture gives an overview of how the JIT compiler fits in Oracle HotSpot JVM. </p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="671" height="541" src="https://zhijunchen.com/wp-content/uploads/2021/04/JIT.png" alt="" class="wp-image-144" srcset="https://zhijunchen.com/wp-content/uploads/2021/04/JIT.png 671w, https://zhijunchen.com/wp-content/uploads/2021/04/JIT-300x242.png 300w" sizes="(max-width: 671px) 100vw, 671px" /></figure>



<p>As you can see, Javac compiler compiles Java source code into an intermediate low-level language (Java Bytecode), which is then run by the java binary. The Java Bytecode cannot be executed by CPUs directly so it will need to be further compiled/interpreted into machine code. And this is where JIT compiler kicks in. When executing Bytecode, the java program is able to compile the code into platform binary as the code executes. That&#8217;s why it is called &#8220;just in time&#8221;.</p>



<p>When the JVM executes code, it does not begin compiling the code immediately. There are two reasons:</p>



<ol><li>Firstly, if the code is going to be executed only once, then compiling it is essentially a wasted effort; it will be faster to interpret the Java bytecodes than to compile them and execute (only once) the compiled code.</li><li>Secondly, the more times that the JVM executes a particular method or loop, the more information it has about that code. This allows the JVM to make numerous optimizations when it compiles the code. The JVM will create compiled code that deals with uncertainty which will involve deoptimizing and then reoptimizing the code in question.</li></ol>



<h2 class="wp-block-heading">On-Stack Replacement</h2>



<p>JIT compilation is an asynchronous process: when the JVM decides that a certain method should be compiled, that method is placed in a queue. Rather than wait for the compilation, the JVM then continues interpreting the method, and the next time the method is called, the JVM will execute the compiled version of the method. But consider a long-running loop. The JVM will notice that the loop itself should be compiled and will queue that code for compilation. But that isn’t sufficient: the JVM has to have the ability to start executing the compiled version of the loop while the loop is still running—it would be inefficient to wait until the loop and enclosing method exit (which may not even happen). Hence, when the code for the loop has finished compiling, the JVM replaces the code (on stack), and the next iteration of the loop will execute the much faster compiled version of the code. This is called <em><strong>on-stack replacement</strong></em> (OSR). </p>



<h2 class="wp-block-heading">Tiered Compilation</h2>



<p>JIT compiler used to have two flavours: client and server compilers. As the name indicates, client compiler (C1) is used for client side applications while server compiler (C2) is used for server side applications. The primary difference between the two compilers is their aggressiveness in compiling code. The C1 compiler begins compiling sooner than the C2 compiler does. This means that during the beginning of code execution, the C1 compiler will be faster. However, C2 compiler makes better optimizations in the compiled code using the knowledge it gains while it waits. Ultimately, code produced by the C2 compiler will be faster than that produced by the C1 compiler. <strong><em>Tiered compilation</em></strong> comes into play by making the JVM start with the C1 compiler and then use the C2 compiler as code gets hotter.</p>



<h2 class="wp-block-heading">Deoptimization</h2>



<p><em><strong>Deoptimization</strong> </em>means that the compiler has to “undo” a previous compilation. The effect is that the performance of the application will be reduced—at least until the compiler can recompile the code in question. Deoptimization occurs in two cases: when code is made not entrant and when code is made zombie. When the compilation log reports that it has made zombie code, it is saying that it has reclaimed previous code that was made not entrant.</p>



<h2 class="wp-block-heading">Code Cache</h2>



<p>When the JVM compiles code, it holds the set of assembly-language instructions in the code cache. The code cache has a fixed size, and once it has filled up, the JVM is not able to compile any additional code. There really isn’t a good mechanism to figure out how much code cache a particular application needs. Hence, when you need to increase the code cache size, it is sort of a hit-and-miss operation; a typical option is to simply double or quadruple the default. </p>



<p>In Java 11, the code cache is segmented into three parts:</p>



<ul><li>Nonmethod code</li><li>Profiled code</li><li>Nonprofiled code</li></ul>



<p>By default, the code cache is sized the same way (up to 240 MB), and you can still adjust the total size of the code cache by using the ReservedCodeCacheSize flag.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Most Useful Java Books And Libraries</title>
		<link>https://zhijunchen.com/most-useful-java-books-and-libraries/</link>
		
		<dc:creator><![CDATA[Zhijun Chen]]></dc:creator>
		<pubDate>Wed, 07 Apr 2021 15:34:41 +0000</pubDate>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://zhijunchen.com/?p=138</guid>

					<description><![CDATA[Java has been my main language since I started programming more than 10 years ago. It has evolved quite a lot over the past years. There are many nice frameworks built around Java, such as Spring, Play, Akka, etc. This post gives a list of books and libraries in my opinion are very useful and would help Java engineers. ]]></description>
										<content:encoded><![CDATA[
<p>Java has been my main language since I started programming more than 10 years ago. It has evolved quite a lot over the past years. There are many nice frameworks built around Java, such as <a rel="noreferrer noopener" href="https://spring.io/" target="_blank">Spring</a>, <a rel="noreferrer noopener" href="https://www.playframework.com/" target="_blank">Play</a>, <a rel="noreferrer noopener" href="https://akka.io/" target="_blank">Akka</a>, etc. This post gives a list of books and libraries in my opinion are very useful and would help Java engineers. </p>



<h2 class="wp-block-heading">Books</h2>



<h5 class="wp-block-heading"><a href="https://www.amazon.co.uk/Effective-Java-Joshua-Bloch/dp/0134685997" target="_blank" rel="noreferrer noopener">Effective Java</a></h5>



<p>In my opinion this is a must-read book for every Java programmer because it includes best practices on pretty much every aspect in Java. But be aware that this is not a beginner&#8217;s book which teaches about syntax. It helps you get to next level once you are comfortable coding in Java. The latest edition of the book is built around Java 7, 8 and 9. You should definitely keep this book on your shelf for references now and then.</p>



<h5 class="wp-block-heading"><a href="https://www.amazon.co.uk/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601" target="_blank" rel="noreferrer noopener">Java Concurrency In Practice</a></h5>



<p>Another must-read book. This is the best Java programming book to develop a rich understanding of concurrency and multithreading. Again this is not a beginner&#8217;s book but advanced programmers will find a lot of valuable insights. Concurrency and multithreading are very tricky to get right and this book would certainly help you write better concurrent code. </p>



<h5 class="wp-block-heading"><a href="https://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" target="_blank" rel="noreferrer noopener">Clean Code</a></h5>



<p>The name says it all. As an engineer, you’ll be reading code ― lots of code. And you will be challenged to think about what’s right about that code, and what’s wrong with it. More importantly, you will be challenged to reassess your professional values and your commitment to your craft.</p>



<p>This book is divided into three parts. The first describes the principles, patterns, and practices of writing clean code. The second part consists of several case studies of increasing complexity. Each case study is an exercise in cleaning up code―of transforming a code base that has some problems into one that is sound and efficient. The third part is the payoff: a single chapter containing a list of heuristics and “smells” gathered while creating the case studies. The result is a knowledge base that describes the way we think when we write, read, and clean code.</p>



<h5 class="wp-block-heading"><a href="https://www.amazon.co.uk/Java-Performance-Definitive-Scott-Oaks/dp/1449358454" target="_blank" rel="noreferrer noopener">Java Performance: The Definitive Guide</a></h5>



<p>Coding and testing are often considered separate areas of expertise. In this comprehensive guide, author and Java expert Scott Oaks takes the approach that anyone who works with Java should be equally adept at understanding how code behaves in the JVM, as well as the tunings likely to help its performance.</p>



<p>You’ll gain in-depth knowledge of Java application performance, using the Java Virtual Machine (JVM) and the Java platform, including the language and API. Developers and performance engineers alike will learn a variety of features, tools, and processes for improving the way Java 7 and 8 applications perform.</p>



<ul><li>Apply four principles for obtaining the best results from performance testing</li><li>Use JDK tools to collect data on how a Java application is performing</li><li>Understand the advantages and disadvantages of using a JIT compiler</li><li>Tune JVM garbage collectors to affect programs as little as possible</li><li>Use techniques to manage heap memory and JVM native memory</li><li>Maximize Java threading and synchronization performance features</li><li>Tackle performance issues in Java EE and Java SE APIs</li><li>Improve Java-driven database application performance</li></ul>



<p></p>



<h2 class="wp-block-heading">Libraries</h2>



<p>The following are Java libraries which I use quite often in my projects. </p>



<h5 class="wp-block-heading"><a href="https://github.com/google/guava" target="_blank" rel="noreferrer noopener">Guava</a></h5>



<p>Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It is widely used on most Java projects within Google, and widely used by many other companies as well.</p>



<p>Guava comes in two flavors.</p>



<ul><li>The JRE flavor requires JDK 1.8 or higher.</li><li>If you need support for JDK 1.7 or Android, use the Android flavor. You can find the Android Guava source in the&nbsp;<a href="https://github.com/google/guava/tree/master/android"><code>android</code>&nbsp;directory</a>.</li></ul>



<h5 class="wp-block-heading"><a href="https://commons.apache.org/" target="_blank" rel="noreferrer noopener">Apache Commons</a></h5>



<p>Apache Commons is an Apache project focused on all aspects of reusable Java components.</p>



<p>The collection is huge and I found the following ones most useful:</p>



<figure class="wp-block-table"><table><thead><tr><th>Component</th><th>Description</th></tr></thead><tbody><tr><td><a href="https://commons.apache.org/proper/commons-io/">IO</a></td><td>Collection of I/O utilities.</td></tr><tr><td><a href="https://commons.apache.org/proper/commons-lang/">Lang</a></td><td>Provides extra functionality for classes in java.lang.</td></tr><tr><td><a href="https://commons.apache.org/proper/commons-csv/">CSV</a></td><td>Component for reading and writing comma separated value files.</td></tr><tr><td><a href="https://commons.apache.org/proper/commons-math/">Math</a></td><td>Lightweight, self-contained mathematics and statistics components.</td></tr></tbody></table></figure>



<h5 class="wp-block-heading"><a href="https://projectlombok.org/" target="_blank" rel="noreferrer noopener">Lombok</a></h5>



<p>Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.<br>Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.</p>



<h5 class="wp-block-heading"><a href="https://github.com/google/dagger" target="_blank" rel="noreferrer noopener">Dagger</a></h5>



<p>A fast dependency injector for Java and Android.</p>



<p>Dagger is a compile-time framework for dependency injection. It uses no reflection or runtime bytecode generation, does all its analysis at compile-time, and generates plain Java source code.</p>



<p>You can <a href="https://dagger.dev/">find the dagger documentation here</a> which has extended usage instructions and other useful information. More detailed information can be found in the <a href="https://dagger.dev/api/latest/">API documentation</a>.</p>



<h5 class="wp-block-heading"><a href="https://github.com/FasterXML/jackson" target="_blank" rel="noreferrer noopener">Jackson</a></h5>



<p>Jackson has been known as &#8220;the Java JSON library&#8221; or &#8220;the best JSON parser for Java&#8221;. Or simply as &#8220;JSON for Java&#8221;.</p>



<p>More than that, Jackson is a suite of data-processing tools for Java (and the JVM platform), including the flagship streaming <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> parser / generator library, matching data-binding library (POJOs to and from JSON) and additional data format modules to process data encoded in <a href="https://github.com/FasterXML/jackson-dataformats-binary/blob/master/avro">Avro</a>, <a href="https://github.com/michel-kraemer/bson4jackson">BSON</a>, <a href="https://github.com/FasterXML/jackson-dataformats-binary/blob/master/cbor">CBOR</a>, <a href="https://github.com/FasterXML/jackson-dataformats-text/blob/master/csv">CSV</a>, <a href="https://github.com/FasterXML/jackson-dataformats-binary/tree/master/smile">Smile</a>, <a href="https://github.com/FasterXML/jackson-dataformats-text/blob/master/properties">(Java) Properties</a>, <a href="https://github.com/FasterXML/jackson-dataformats-binary/tree/master/protobuf">Protobuf</a>, <a href="https://github.com/FasterXML/jackson-dataformat-xml">XML</a> or <a href="https://github.com/FasterXML/jackson-dataformats-text/blob/master/yaml">YAML</a>; and even the large set of data format modules to support data types of widely used data types such as <a href="https://github.com/FasterXML/jackson-datatypes-collections">Guava</a>, <a href="https://github.com/FasterXML/jackson-datatype-joda">Joda</a>, <a href="https://github.com/FasterXML/jackson-datatypes-collections">PCollections</a> and many, many more.</p>



<p>While the actual core components live under their own projects &#8212; including the three core packages (<a href="https://github.com/FasterXML/jackson-core">streaming</a>,&nbsp;<a href="https://github.com/FasterXML/jackson-databind">databind</a>,&nbsp;<a href="https://github.com/FasterXML/jackson-annotations">annotations</a>); data format libraries; data type libraries;&nbsp;<a href="https://github.com/FasterXML/jackson-jaxrs-providers">JAX-RS provider</a>; and a miscellaneous set of other extension modules &#8212; this project act as the central hub for linking all the pieces together.</p>



<h5 class="wp-block-heading"><a href="https://junit.org/junit5/docs/current/user-guide/" target="_blank" rel="noreferrer noopener">JUnit 5</a></h5>



<p>Unlike previous versions of JUnit, JUnit 5 is composed of several different modules from three different sub-projects.</p>



<p><strong>JUnit 5 =&nbsp;<em>JUnit Platform</em>&nbsp;+&nbsp;<em>JUnit Jupiter</em>&nbsp;+&nbsp;<em>JUnit Vintage</em></strong></p>



<p>The&nbsp;<strong>JUnit Platform</strong>&nbsp;serves as a foundation for&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#launcher-api">launching testing frameworks</a>&nbsp;on the JVM. It also defines the&nbsp;<code><a href="https://junit.org/junit5/docs/current/api/org.junit.platform.engine/org/junit/platform/engine/TestEngine.html">TestEngine</a></code>&nbsp;API for developing a testing framework that runs on the platform. Furthermore, the platform provides a&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher">Console Launcher</a>&nbsp;to launch the platform from the command line and a&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-junit-platform-runner">JUnit 4 based Runner</a>&nbsp;for running any&nbsp;<code>TestEngine</code>&nbsp;on the platform in a JUnit 4 based environment. First-class support for the JUnit Platform also exists in popular IDEs (see&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-ide-intellij-idea">IntelliJ IDEA</a>,&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-ide-eclipse">Eclipse</a>,&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-ide-netbeans">NetBeans</a>, and&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-ide-vscode">Visual Studio Code</a>) and build tools (see&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-build-gradle">Gradle</a>,&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-build-maven">Maven</a>, and&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-build-ant">Ant</a>).</p>



<p><strong>JUnit Jupiter</strong>&nbsp;is the combination of the new&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#writing-tests">programming model</a>&nbsp;and&nbsp;<a href="https://junit.org/junit5/docs/current/user-guide/#extensions">extension model</a>&nbsp;for writing tests and extensions in JUnit 5. The Jupiter sub-project provides a&nbsp;<code>TestEngine</code>&nbsp;for running Jupiter based tests on the platform.</p>



<p><strong>JUnit Vintage</strong>&nbsp;provides a&nbsp;<code>TestEngine</code>&nbsp;for running JUnit 3 and JUnit 4 based tests on the platform.</p>



<h5 class="wp-block-heading"><a href="https://github.com/awaitility/awaitility" target="_blank" rel="noreferrer noopener">Awaitility</a></h5>



<p>Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaitility is a DSL that allows you to express expectations of an asynchronous system in a concise and easy to read manner. For example:</p>



<pre class="wp-block-code"><code>@Test
public void updatesCustomerStatus() {
    // Publish an asynchronous message to a broker (e.g. RabbitMQ):
    messageBroker.publishMessage(updateCustomerStatusMessage);
    // Awaitility lets you wait until the asynchronous operation completes:
    await().atMost(5, SECONDS).until(customerStatusIsUpdated());
    ...
}</code></pre>



<h5 class="wp-block-heading"><a href="https://assertj.github.io/doc/" target="_blank" rel="noreferrer noopener">AssertJ</a></h5>



<p>AssertJ is a java library providing a rich set of assertions, truly helpful error messages, improves test code readability and is designed to be super easy to use within your favorite IDE.</p>



<p>Here are a few examples of AssertJ assertions:</p>



<pre class="wp-block-code"><code>// entry point for all assertThat methods and utility methods (e.g. entry)
import static org.assertj.core.api.Assertions.*;

// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);

// chaining string specific assertions
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");

// collection specific assertions (there are plenty more)
// in the examples below fellowshipOfTheRing is a List&lt;TolkienCharacter>
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);

// as() is used to describe the test and will be shown before the error message
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);

// exception assertion, standard style ...
assertThatThrownBy(() -> { throw new Exception("boom!"); }).hasMessage("boom!");
// ... or BDD style
Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); });
assertThat(thrown).hasMessageContaining("boom");

// using the 'extracting' feature to check fellowshipOfTheRing character's names
assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName)
                               .doesNotContain("Sauron", "Elrond");

// extracting multiple values at once grouped in tuples
assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
                               .contains(tuple("Boromir", 37, "Man"),
                                         tuple("Sam", 38, "Hobbit"),
                                         tuple("Legolas", 1000, "Elf"));

// filtering a collection before asserting
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
                               .containsOnly(aragorn, frodo, legolas, boromir);

// combining filtering and extraction (yes we can)
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
                               .containsOnly(aragorn, frodo, legolas, boromir)
                               .extracting(character -> character.getRace().getName())
                               .contains("Hobbit", "Elf", "Man");

// and many more assertions: iterable, stream, array, map, dates, path, file, numbers, predicate, optional ...</code></pre>



<h5 class="wp-block-heading"><a href="https://github.com/mockito/mockito" target="_blank" rel="noreferrer noopener">Mockito</a></h5>



<p>Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with a clean &amp; simple API. Mockito doesn’t give you hangover because the tests are very readable and they produce clean verification errors.</p>



<p>In mockito, we generally work with following kind of test doubles.</p>



<ul><li><strong>Stubs</strong>&nbsp;– is an object that has predefined return values to method executions made during the test.</li><li><strong>Spies</strong>&nbsp;– are objects that are similar to stubs, but they additionally record how they were executed.</li><li><strong>Mocks</strong>&nbsp;– are objects that have return values to method executions made during the test and has recorded expectations of these executions. Mocks can throw an exception if they receive a call they don’t expect and are checked during verification to ensure they got all the calls they were expecting.</li></ul>



<p>We can mock both interfaces and classes in the test class. Mockito also helps to produce minimum boilerplate code while using mockito annotations.</p>



<h5 class="wp-block-heading"><a href="https://github.com/mapstruct/mapstruct" target="_blank" rel="noreferrer noopener">Mapstruct</a></h5>



<p>MapStruct is a Java&nbsp;<a href="http://docs.oracle.com/javase/6/docs/technotes/guides/apt/index.html">annotation processor</a>&nbsp;for the generation of type-safe and performant mappers for Java bean classes. It saves you from writing mapping code by hand, which is a tedious and error-prone task. The generator comes with sensible defaults and many built-in type conversions, but it steps out of your way when it comes to configuring or implementing special behavior.</p>



<p>Compared to mapping frameworks working at runtime, MapStruct offers the following advantages:</p>



<ul><li><strong>Fast execution</strong>&nbsp;by using plain method invocations instead of reflection</li><li><strong>Compile-time type safety</strong>. Only objects and attributes mapping to each other can be mapped, so there&#8217;s no accidental mapping of an order entity into a customer DTO, etc.</li><li><strong>Self-contained code</strong>—no runtime dependencies</li><li><strong>Clear error reports</strong>&nbsp;at build time if:<ul><li>mappings are incomplete (not all target properties are mapped)</li><li>mappings are incorrect (cannot find a proper mapping method or type conversion)</li></ul></li><li><strong>Easily debuggable mapping code</strong>&nbsp;(or editable by hand—e.g. in case of a bug in the generator)</li></ul>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
