Instancio: Random Test Data Generator for Java (Part 1)

By now hopefully all of us, developers, have embraced unit testing. Good test coverage of our codebase, combined with that green checkmark after running the tests, gives us a warm fuzzy feeling that everything is in order. While we all like that warm fuzzy feeling, writing tests usually requires some plumbing. This is the "boring part", where you create your test objects and manually set them up with dummy data. Oftentimes the values themselves don't even matter. A typical example of this is testing "converter" logic. For example, we might be converting a JPA entity to a DTO, or a JAXB class to something else. Such a test might look something like this:

Java
 
@Test
void verifyCustomer() {
  Customer customer = new Customer();
  customer.setFirstName("John");
  customer.setLastName("Doe");
  customer.setAddress(new Address("123 Main St", "Seattle", "US"));
  customer.setPhoneNumbers(List.of(
    new Phone(PhoneType.HOME, "+1", "123-44-55"),
    new Phone(PhoneType.WORK, "+1", "555-77-88")));
  // ... etc
  
  CustomerDTO customerDto = customerMapper.toDto(customer);
  
  assertThat(customerDto.getFirstName()).isEqualTo(customer.getFirstName());
  assertThat(customerDto.getLastName()).isEqualTo(customer.getLastName());
  // ... etc
}


Why Don’t Developers Write More Tests?

I regularly speak at conferences about testing microservices, and one of the first questions I ask attendees is whether they write tests or not. The room is usually split 50-50 between developers who write tests for their code and those who do not. This disparity gets more pronounced when I give guest lectures at coding bootcamps where I’ve found that fewer than 1 in 10 grads actually know how to write a unit test.

My anecdotal observations have been backed up by surveys as well. Diffblue found 42% of developers skip writing tests and Stack Overflow found 37% of developers don’t write tests for their code at work.

Simple code: Simplicity

Simplest solutions are usually the best solutions.

We as software developers work with hard problems and solve a lot of small problems every day. Solving a hard problem itself is a hard job. Though in my opinion it's not enough to solve a hard problem in any possible way but a hard problem should be solved with a simple solution. When a developer comes up with a simple solution to a hard problem then they can declare the problem solved.

First a disclaimer. Coming up with a simple solution to a hard problems is itself a very hard problem and takes a lot of time, effort and practice.

I've seen my share of "clever" solutions for hard problems and the problem with those is that usually the solution itself is so hard to understand that depending on the size of the problem it may take a developer from hours to days or even weeks to understand how that "clever" solution works. It's a rare occasion when a developer has come up with a simple solution to a hard problem. So simple that it needs to be read only once and it makes sense. I dare to say I've made a few of these solutions and I've also seen these from other developers but way less often than hard to understand solutions for hard problems.

So how does one come up with simple solutions to hard problems?
First step is to split the problem to smaller problems. How this works for me is that I try to identify smaller problem areas within the original problem. Once I have identified smaller problems I can usually find yet smaller problems to solve within those and I continue to do it until I have a plan, a set of tasks or small problems to solve. Usually I identify even more problems to solve once I start to work on them and I just add them to the list of small problems to solve. With this iterative process I can solve the problem one small piece at a time.

Splitting the problem to multiple smaller problems gives other benefits too. Each small problem can be tested individually and the big problem's tests work as acceptance tests for the whole set of small problems. Smaller problems are easier to solve and therefore the code is easier to write and when the code is easier to write it's easier to write readable code.

In a ideal situation the big problem would be solved by sequentially calling functions that solve a smaller problem within the problem space. In a way it could be thought like the solution to a problem can be solved by a function introduced in a interface. That interface is tested with a acceptance tests and it can be tested with mocks or spies to verify it calls the correct functions in correct order with correct parameters. The implementation of the interface is actually a series of function calls that each solve a portion of the problem. Each of those functions is tested with unit tests. Each of functions can be written as easily readable by keeping them small and naming the functions and things within those functions meaningfully. When a function is small and solves a single problem the solution is easy to define with immutable data structures or by avoiding mutating the variables. Also when each function works as it's own unit it's easier to isolate integration tests to those functions.

This is how simple solutions are crafted and this is how all the topics I have covered earlier are tied together to create simple, readable, verified and long lasting solutions to problems.

With all this tied up what started with a working title "My version of clean code" could also be simplified and after thinking about it more while writing these posts I decided to name the approach and conventions as "Simple code".


Getting Started With WebdriverIO Typescript Jasmine

What is WebdriverIO?

WebdriverIO is a progressive automation framework built to automate modern web and mobile applications. It simplifies the interaction with your app and provides a set of plugins that help you create a scalable, robust, and flakiness test suite. WebdriverIO is built on top of Selenium NodeJS bindings.

Webdriver IO is Open Source Framework managed by OpenJS foundation and follows W3 framework architectural standards

Simple Code: Unit Tests

Unit tests are the developer's number one safety net. Let that sink in. This is the number one reason for writing unit tests.

Unit tests are written by developers for developers to ensure that the code works as expected and handles happy and sad paths correctly. With enough unit test coverage, the tests enable a safe environment for refactoring and rewriting code.

Simple Code: Immutability

Immutability is a special thing that in my mind deserves a short explanation and praise.
If you're familiar with functional programming you surely recognize the concept of immutability because it's a key ingredient of the paradigm. In the world of object-oriented programming, it's not as used and as easy to use approach but there are ways to incorporate immutability to parts of the code and I strongly suggest you do so too.

Quick Intro to Immutability

The basic idea of immutability is unchangeable data. 

Simple Code: Contracts

What Are Contracts?

A high abstraction level of contracts for code is APIs. They define an interface that is basically a contract that the producer and consumer of the API agree to use to communicate with each other. Two common forms of APIs are libraries that are used in code and external APIs that are used via HTTP, RPC, etc.

When thinking a bit deeper, contracts consist firstly of functions, methods, or external endpoints and secondly of data, more precisely on data models and data types within the models.

Your Simple Coding Guide: Functions and Methods

What makes a good function or method? It's not just one thing, but rather a combination of things where each is significant. If something is flawed, it affects the whole function. So what are these common slip-ups, and how can you avoid them?

It Has a Meaningful Name

Functions should have names that describes their purpose or functionality. When a function has a meaningful name, it's easy to read and understand its purpose.

For example, if a function's purpose is to find a customer by ID, a good name could be findCustomerById(id: String). It could also just as well be findCustomer(id: String) because the function signature implies that the customer is found by their ID. The word find also implies that the customer might be found or it might not be found.

If the function's name would be changed to getCustomer(id: String), its meaning changes because now it implies that there's no fallback; the customer is either found or the function fails miserably and maybe throws an exception.

Both are valid names for a function but they have a different meaning and therefore their implementations should also be different.

Unit Testing Static Methods With Mockito

Unit testing helps us to cover different scenarios and it is a way to ensure the applications behave as expected under certain circumstances. Most of the time it is easy to test your classes and methods, but sometimes you need to mock certain services or methods to isolate your target. Mockito is a good library to help you with that. It can easily create mocked or partially mocked objects for you with Mockito#mock or with Mockito#spy.

There are some cases that we also want to mock static methods of a particular utility class, so how can we accomplish that? Well by using the Mockito mockStatic method. Lets take an example by using the following AnimalUtils, Dog objects and Animal Interface:

Don’t Use assertTrue to Verify Text in Your Test

Introduction

It is common, especially in functional tests on any front-end (web, mobile), to include text validation in our tests to verify that the returned value is the expected one. These validations are user failures or even information about a successfully executed command.

However, it is common to see many professionals using the assertTrue command instead of assertEquals to validate the returned text.

How to Mock a Rest API in Python

A few posts ago, we published a blog about how to use the Jira API. We did not write any unit tests for the application we wrote, and that is exactly what we are going to do now. More specifically, we will focus on how we can unit test a REST API.

Why Unit Tests Anyway?

Our main focus when writing software is building new features and fixing bugs. Of course, we need to test what we built, but we get the most joyful moment when our newly developed feature works. The next step is to write unit tests… But, we already know it is working, so why spend so much effort on it? It is much more fun to start with the next feature, right? So, we skip writing unit tests. But what happens when we need to extend the feature we wrote with some new functionality? 

Clean Unit Testing

It's easy to write "unit tests" that use JUnit and some mocking library.  They may produce code coverage that keep some stakeholders happy, even though the tests may not even be unit tests and the test may provide questionable value.  It can also be very easy to write unit tests that are (in theory) units test but are far more complex than the underlying code and hence just add to the total software entropy.

This particular type of software entropy has the unpleasant characteristic of making it even harder for the underlying software to be restructured or to surface new requirements. It is like the test has a negative value.

Unit Testing Log Messages Made Easy

As Java developers, we need to cover a lot of scenarios to ensure the quality of our software and catch bugs as soon as possible when introducing new code. For 99% of all my use cases, AssertJ, JUnit, Mockito, and Wiremock are sufficient enough to cover the test cases. But for the other use cases, like unit testing info, debugging or warning log messages, these frameworks don't help you out. There is also no other framework that can provide an easy to use method to capture log messages.

The answer which the community provided works well, but it needs a lot of boilerplate code to just assert your log events. So, I wanted to make it easier for myself and share it with you! This is how the LogCaptor library came into life.

MUnit Towards Automated Unit Test Cases

Test beakers
Find out how to use MUnit with Mule for automated unit testing.

Why Unit Testing?

This is the first question most beginners ask when they struggle to relate unit test cases with real scenarios, like what value-added unit testing is doing. This was my first thought after reading JUnit documents fifteen years back. I am sure most new developers would have similar feelings after reading unit test documents alone, but I realized that unit testing is a powerful tool to release defect-free code to production. The unit testing helps to do regression testing and gives confidence for new developers to make changes to the old codebase.

MUnit For Mule Flows

MUnit is an extension of JUnit. Developers are allowed to write XML-based test cases or Java code-based test cases for Mule flows. This document covers MUnit basics, practical options for different scenarios, and automating the business validations.

Beginners Guide to Mocking in Scala

We all know that unit test cases are one of the most important parts of an application. No? Then, I must tell you that unit testing is one of the earliest tests to be performed on the unit of code, and the earlier the defects are detected, the easier it is to fix. It reduces the difficulties of discovering errors contained in more complex pieces of the application.

So where does mocking come into the picture? Why do we need it? And how do we understand what we should mock while writing unit test cases? Answers to these questions are right below in this blog.

Unit Test Insanity

Are you repeating your unit tests in an effort to expect a different result?

While moving our daughter into her new apartment, which happens to be on the 9th floor of the rental complex, I noticed an interesting situation while waiting for the elevator to arrive. As others walked up to wait for the elevator, they would push the button with the universal "arrow pointing up" symbol — even though we had already pushed the button to request the elevator's service.