Unit Testing using GIVEN-WHEN-THEN Template(Part 1: Introduction)

What is Unit Testing?

“Unit” can be defined as the smallest complete part of something. In this case, “unit” is a function or method of the system. Hence Unit Testing is a testing scenario for each function or method. Unit testing is automated and considered the cheapest one and the lowest part of the Test Pyramid.

Unit Testing in the overall testing process

Testing can be a complicated process and at least serve for 2 purposes, first to ensure the software or system is not crashed (a.k.a System Testing) and to make sure whether the solution meets with the user need (a.k.a User Acceptance Test/UAT)

Why need to write Unit Testing?

  1. A safety-net
    Unit Testing is mandatory when coming with CI/CD. Without such a mechanism like automated testing as a safety-net, who can guarantee we not deploy a defective service.
  2. Documentation
    Unit Testing also can consider better internal documentation than comments. It provides sample input and output, prerequisite to called the function and dependency
  3. Efficiency
    Unit Testing can save a lot of time because the coder only needs to focus on a single unit without worrying it will break another part of the project (Well, at least we know if something broken). The coder can jump directly to test to a specific function/method rather than from program entry-point (the main() function)
  4. Code Quality
    Existence of Unit Testing is one sign of a good project. Unit Testing not only said that the function/method is really working but in the process of writing it, it will affect and drive the entire project to good design.

Test-driven Development

Unit Testing is more than a mere tool to verify/ensure the functionality but rather a blueprint of logical thinking. Only if you believe on this then Test-driven Development (TDD) can give its full merit. In short, TDD is about design not testing.

Make specification for a function

Unit Testing is a thought process before the code, in other words, testing is a specification for the function. However, the function itself has inter-correlation each other. How we manage the specification?

function A(){
B(); // call function B
// Do something else
}
function B(){
// Do something
}

Behaviour-driven Development

Rather than focus on each function, it more makes sense to write on the overall behavioral expectation of the system and this approach called Behaviour-driver Development (BDD).

Given-When-Then

This is a typical format of GWT

GIVEN a context
WHEN some condition
THEN expect some output

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Iman Tung

Iman Tung

Technology to write, life to grateful. Overthinking is good, only if it has the output. Fundamental is the main concern.