2

Java developer testing toolbox

JBehave : code

An article dealing with Java application and testing frameworks and related libraries. Continue Reading

0

Test and Data Generation for Java Unit tests

Today I was preparing a presentation about Software Code quality for a TechTalk on Thursday. I made a search on Internet about Automatic Unit test generator and Data Generators. I will present some tools I have tried. Today, we will speak of Randoop.

Randoom Test Generator

Randoom Test Generator

The first tool name is Randoop.. This tool is existing since 2007 and its purpose is to generate automatically unit tests 🙂 Directly from your class definition!

To use it you have two choices:

  • You can use your software JAR or classpath directory.
  • You can include it in your test compile path (on gradle or maven) and creates a main or unit test.

To explain short the theory, thanks to the Java reflection it’s quite easy to produce automatic tests validating some contracts of your API.

Some examples: – toString() should never returns null or throws an Exception – equals() and compareTo() methods have a long list of constraints – Reflexivity: o.equals(o) == true – Symmetry: o1.equals(o2) == o2.equals(o1) – Transitivity: o1.equals(o2) && o2.equals(o3) ⇒ o1.equals(o3) – Equals to null: o.equals(null) == false – It does not throw an exception

Therefore this tool is generating unit tests with JUnit(TestSuite) for the list of classes you provide.

I have done some tests and you can reach 50-60% of coverage quite easily.

The main drawbacks of the solution are: – The unit tests are drawing a snapshot (precise picture) of your code and its behaviour however some tests are really non-sense and you don’t want to edit them. – They don’t replace handwritten tests since the tool is not understand the different between a String parameter emailand fullName. He will mostly use dumb strings.

About the technology, it’s not production ready: – I had troubles with the jar and its dependency plume. – The JAR is a fatjar and coming with dependencies that broke my software.

In conclusion, I will fork the software and try to fix the problems to make it more popular 🙂

1

SonarQube and ReactJS

This article is showing you how to use SonarQube with ReactJS and its JSX files. I will use both SonarQube JavaScript plugin and the additional plugin Sonar EsLint plugin.

<%- toc(str, [options]) %>

For the people who has missed my previous article, I have created a new SonarQube plugin to extends the Javascript analysis.

Installation and Configuration

The first step is to download the plugin directly from Github here.

Download the plugin

Download the plugin

Find the latest release.

Find the latest release

Find the latest release

Copy it in your Sonar extension folder.

Copy the plugin

Copy the plugin

Restart the server

Restart the server by calling the commands (here on linux)

sonarqube-6.0 ./bin/linux-x86-64/sonar.sh stop
  Stopping SonarQube...
  Waiting for SonarQube to exit...
  Stopped SonarQube.
  ➜  sonarqube-6.0 ./bin/linux-x86-64/sonar.sh start

 Enabling custom rules in SonarQube

Don’t forget to modify your SonarQube profile to enable the new ESLint rules :

Add the ESLint rules to your SonarQube profile

Add the ESLint rules to your SonarQube profile

Enable the ESLint rules to your SonarQube profile

Enable the ESLint rules to your SonarQube profile

Preparing your project

 Handling SonarQube Scanner

Most projects requires the SonarQube scanner (Wiki Link to analysis Javascript. Download it somewhere on your disk and unzip it.

Creates a file sonar-project.properties̀ into your project.

Copy-paste this content and modify it :

sonar.projectKey=sleroy:reactjs-demo
sonar.projectName=ReactJS demo
sonar.projectVersion=1.0
sonar.sources=src
sonar.sourceEncoding=UTF-8
sonar.javascript.file.suffixes=.js,.jsx

Don’t forget the line sonar.javascript.file.suffixes=.js,.jsx, it’s the hack to make SonarQube working on JSX files!

OK! SonarQube Scanner is configured!

Preparing ESLint

We want to perform the SonarQube analysis with the additional results of ESLint. Eslint is a popular linter that provides recent rules for many javascript frameworks – ReactJS included.

ESLint is thereby often upgraded and contains through its extension system, rules and frameworks that you won’t find in the regular SonarQube installation.

If you haven’t created yet an ESLint configuration file, here is the commands :

ESLint Configuration

ESLint Configuration

You can try the configuration by launching ESLint ony your project. It may warn you that some extensions are missing. Install them with NPM or Yarn.

Missing NPM Module

Missing NPM Module

Usually, the ReactJS extension is missing of your project. You can add them like developer extensions (--save-dev) or globally (-g).

Install missing ESLINT ReactJS extension

Install missing ESLINT ReactJS extension

With the right configuration and ESLint installation, the scan of a JSX File should work :

Scanning JSX File

Scanning JSX File

OK! ESLint is configured!

 Launching SonarQube Scanner

Launchs the SonarQube scanner with the command :

~/tools/sscanner/bin/sonar-scanner

And the analysis is running …

react-jsx git:(master) ✗ ~/tools/sscanner/bin/sonar-scanner
INFO: Scanner configuration file: /home/sleroy/tools/sscanner/conf/sonar-scanner.properties
INFO: Project root configuration file: /home/sleroy/git/react-jsx/sonar-project.properties
INFO: SonarQube Scanner 3.0.3.778
INFO: Java 1.8.0_121 Oracle Corporation (64-bit)
INFO: Linux 4.10.0-21-generic amd64
INFO: User cache: /home/sleroy/.sonar/cache
INFO: Load global repositories
INFO: Load global repositories (done) | time=211ms
INFO: User cache: /home/sleroy/.sonar/cache
INFO: Load plugins index
INFO: Load plugins index (done) | time=14ms
INFO: SonarQube server 6.0
INFO: Default locale: "fr_FR", source code encoding: "UTF-8" (analysis is platform dependent)
INFO: Process project properties
INFO: Load project repositories
INFO: Load project repositories (done) | time=214ms
INFO: Load quality profiles
INFO: Load quality profiles (done) | time=94ms
INFO: Load active rules
INFO: Load active rules (done) | time=897ms
INFO: Publish mode
INFO: -------------  Scan ReactJS demo
INFO: Load server rules
INFO: Load server rules (done) | time=482ms
INFO: Base dir: /home/sleroy/git/react-jsx
INFO: Working dir: /home/sleroy/git/react-jsx/.scannerwork
INFO: Source paths: src
INFO: Source encoding: UTF-8, default locale: fr_FR
INFO: Index files
INFO: 9 files indexed
INFO: Quality profile for js: Sonar way
INFO: Sensor Lines Sensor
INFO: Sensor Lines Sensor (done) | time=41ms
INFO: Sensor SCM Sensor
INFO: SCM provider for this project is: git
INFO: 9 files to be analyzed
INFO: 0/9 files analyzed
WARN: Missing blame information for the following files:
WARN:   * /home/sleroy/git/react-jsx/src/example/hello.jsx
WARN:   * /home/sleroy/git/react-jsx/src/example/index.jsx
WARN:   * /home/sleroy/git/react-jsx/src/fixtures/this.jsx
WARN:   * /home/sleroy/git/react-jsx/src/example/index.js
WARN:   * /home/sleroy/git/react-jsx/src/example/imager.jsx
WARN:   * /home/sleroy/git/react-jsx/src/fixtures/component.jsx
WARN:   * /home/sleroy/git/react-jsx/src/fixtures/advanced.jsx
WARN:   * /home/sleroy/git/react-jsx/src/fixtures/react.jsx
WARN:   * /home/sleroy/git/react-jsx/src/fixtures/hello.jsx
WARN: This may lead to missing/broken features in SonarQube
INFO: Sensor SCM Sensor (done) | time=504ms
INFO: Sensor XmlFileSensor
INFO: Sensor XmlFileSensor (done) | time=1ms
INFO: Sensor JavaScript Squid Sensor
INFO: 9 source files to be analyzed
INFO: 9/9 source files have been analyzed
INFO: Unit Test Coverage Sensor is started
INFO: Integration Test Coverage Sensor is started
INFO: Overall Coverage Sensor is started
INFO: Sensor JavaScript Squid Sensor (done) | time=893ms
INFO: Sensor Linting sensor for Javascript files
INFO: Sensor Linting sensor for Javascript files (done) | time=1438ms
INFO: Sensor Zero Coverage Sensor
INFO: Sensor Zero Coverage Sensor (done) | time=38ms
INFO: Sensor Code Colorizer Sensor
INFO: Sensor Code Colorizer Sensor (done) | time=2ms
INFO: Sensor CPD Block Indexer
INFO: DefaultCpdBlockIndexer is used for js
INFO: Sensor CPD Block Indexer (done) | time=1ms
INFO: Calculating CPD for 2 files
INFO: CPD calculation finished
INFO: Analysis report generated in 170ms, dir size=24 KB
INFO: Analysis reports compressed in 254ms, zip size=18 KB
INFO: Analysis report uploaded in 39ms
INFO: ANALYSIS SUCCESSFUL, you can browse http://localhost:9000/dashboard/index/sleroy:reactjs-demo
INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
INFO: More about the report processing at http://localhost:9000/api/ce/task?id=AVwHr7JyDHBkCqlFC7Sx
INFO: Task total time: 8.046 s
INFO: ------------------------------------------------------------------------
INFO: EXECUTION SUCCESS
INFO: ------------------------------------------------------------------------
INFO: Total time: 10.141s
INFO: Final Memory: 48M/301M
INFO: ------------------------------------------------------------------------

Controlling the results

Go to your Sonar interface, and jump directly to the dashboard.

Our project has been analyzed.

SonarQube analysis

SonarQube analysis

We observe that the violation’s number is increasing with the new rules.

SonarQube analysis details

SonarQube analysis details

Hourra, our JSX files are analyzed !

JSX Analysis

JSX Analysis

In this article, we have installed, configured a new plugin to perform better Javascript analysis into SonarQube, working with ReactJS and JSX files.

0

Release of FakeSmtp-junit-runner

Today, I released a new library to help developers to write integration tests with mail servers.

The library has been released on GitHub and Maven Central.

fakesmtp-junit-runner

Build Status

Coverage Status

Links : github.

Important : Part of the source code of this library has been modified and adapted from the project of FakeSmtp. I want to thank him since his project inspired me the creation of that library.

This library is an extension to JUnit to allow developers to write integration tests where a SMTP server is required.

The how-to is quite simple :

  • Inserts the @Rule in your integration tests
  • a Fake SMTP Server will start
  • You can send mails on it
  • You can control the mailbox
  • Write your own assertions to check mails.

Installation

The project requires JUnit 4.11 or higher. It also requires SLF4J API presents in the classpath. I did not bundle them in the library to avoid conflicts.

To use it, adds the library to your maven or gradle config script :

For maven :

<dependency>
  <groupId>com.github.sleroy</groupId>
  <artifactId>fakesmtp-junit-runner</artifactId>
  <version>0.1.1</version>
  <scope>test</scope>
</dependency>

For gradle :

testCompile "com.github.sleroy:fakesmtp-junit-runner:0.1.1"

Usage

Step 1 :

Creates a JUnit test :

public class SmtpSendingClassTest {


  @Test
  public void testCase1() {

  }

}

Step 2 :

Adds the new Junit rule with its configuration :

public class SmtpSendingClassTest {

  @Rule
    public FakeSmtpRule smtpServer = new FakeSmtpRule(ServerConfiguration.create().port(2525).charset("UTF-8"));

  @Test
  public void testCase1() {

  }

}

Step 3 :

You are ready to use it, controls the mailbox or the server state :

Assert.assertTrue(smtpServer.isRunning());
public class SmtpSendingClassTest {

  @Rule
    public FakeSmtpRule smtpServer = new FakeSmtpRule(ServerConfiguration.create().port(2525).charset("UTF-8"));

  @Test
  public void testCase1() {
    Assert.assertTrue(smtpServer.isRunning());
    Assert.assertTrue(smtpServer.mailbox().isEmpty());
  }

}
0

My weekly DZone”s digest #1

This is my first post that offers a digest from a selection of DZone’s articles. I will pick DZone’s article based on my interests.

This week the subjects are : BDD Testing, Bad code, Database Connection Pooling, Kotlin, Enterprise Architecture

A few benefits you get by doing BDD

A few benefits you get by doing BDD : This article is an introduction to the Behaviour Driven Development practice. It’s interesting because we are regularly meeting teams, developers, architectures (pick your favorite one) that are confusing technical details and functionalities. As a result, the design, the tests and the architecture hides the user behaviour (the use cases ?) under a pile of technical stones. This article is a nice introduction. I recommend to go further these articles : * Your boss won’t appreciate tdd, try BDD * BDD Programming Frameworks * Java Framework JBehave.

Gumption Traps: Bad Code

Bad code, how my code...

Bad code, how my code…

Gumption Traps: Bad Code : an article about the bad code and how to deal with it.

{% blockquote Grzegorz Ziemoński%} The first step to avoid the bad code trap is to stop producing such code yourself. When faced with existing bad code,one must work smart to maintain motivation. {% endblockquote %}

This is a good introduction sentence. This week, I had a meeting with a skilled and amazing team. The meeting’s goal was to find a way to find the technical debt. The very technical debt that is ruining the application and undermining the team’s motivation. What I found interesting and refreshing in this article, is the pragmatic tone and the advice.

{% blockquote Grzegorz Ziemoński%} To avoid bad code, try to minimize the amount of newly produced bad code. {% endblockquote %}

How to avoid the depress linked to the bad code ? First of all, I want to say that developers are not receiving enough training on how to improve the code. Usually university / college courses are dedicated about How to use a framework. Therefore, few of them are able to qualify what is a bad code, what are its characteristics and de facto the ways to improve it. To avoid bad code, I try to demonstrate the personal benefits for the developers to improve their skills. Quality is not only a question of money (how much the customer is paying) but rather how much your company is paying attention to your training and personal development.

A lot of developers are overwhelmed under the technical debts without the appropriate tools (mind, technics, theory) to handle it. I try to give them gumptions about the benefits to be a better developer and how to handle the weakness of a sick application. To save a software rather than practicing euthanasia 🙂

Database Connection Pooling in Java With HikariCP

When we are discussing about Database connection pooling, most of my colleagues are relying on the good old Tomcat dbcp. However there is a niche, really funny and interesting, the guys that a competing for the best DBCP. And HikariCP is clearly a step ahead of everyone.

The article Database Connection Pooling in Java With HikariCP is presenting how to use a custom DBCP in your software.

Hikari Performance

Hikari Performance

I think it would have been great to present the differences with the standard DBCP and further debate on the advantages/disadvantages of the solutions. A good idea for a newt article 🙂

Concurrency: Java Futures and Kotlin Coroutines

Java Futures and Kotlin Coroutines An interesting article about how Java Futures and Kotlin co-routines can coexists. Honestly I am a little bit disappointed and thought that Kotlin would make things easier like in Node.JS

Are Code Rules Meant to Be Broken?

Another article about Code Quality and we could be dubious whether exists an answer to that question : Are Code Rules Meant to Be Broken.

I won’t enter too much in the details, the author’s point of view seems to be Code Rules are good if they are respected. If they are broken, it implies that the Code rules need to evolve 🙂 What do you think about it ?

Java vs. Kotlin: First Impressions Using Kotlin for a Commercial Android Project

This article is interesting since it presents a feedback session on using Kotlin in a Android project.

The following big PLUS to use Kotlin are :

  • Null safety through nullable and non-nullable types, safe calls, and safe casts.
  • Extension functions.
  • Higher-order functions / lambda expressions.
  • Data classes.
  • Immutability.
  • Coroutines (added on Kotlin 1.1).
  • Type aliases (added on Kotlin 1.1).

  Quality Code Is Loosely Coupled

Quality Code Is Loosely Coupled

This article is explaining one of the most dangerous side of coding : Coupling. Must to read article despite the lack of schemas.

Five Habits That Help Code Quality

This article is a great introduction on code assessment. These five habits are indeed things to track in your software code as a sign of decay and code sickness.

The habits are : – Write (Useful) Unit Tests – Keep Coupling to a Minimum – Be Mindful of the Principle of Least Astonishment – Minimize Cyclomatic Complexity – Get Names Right

10 Good Excuses for Not Reusing Enterprise Code

This article is really useful in the context of Digital Transformation to assess which softwares you should keep and throw.

Example of excuses : – I didn’t know that code existed. – I don’t know what that code does. – I don’t know how to use that code. – That code is not packaged in a reusable manner.

Test proven design

An interesting article and example on how to improve your own code using different skills. I really recommend to read this article and the next future ones : Test proven design.