How to write your first Unit Test | In Different programming languages.

Deepak Vishwakarma
Geek Culture
Published in
6 min readNov 12, 2019

In the past few years of experience, I have done coding in various languages. Most of the time (Except POCs), I had to write the test cases for myself. Sometimes, I had to write test cases for other code too [I really hate it].

There are many challenges while setting up the test framework. Here I will explain how to set up a basic test environment for Unit Tests for well-known programming languages.

Photo by Science in HD on Unsplash

NodeJs/JavaScript: JavaScript is the most used language today. Thanks to node js eco-system and its simplicity, we have lots of frameworks/scaffolding tools. It is easy to set any kind of environment.

To create a full working setup, you can use generators like Yeoman. Some other frameworks like React, Angular, provide the test environment setup with generated code. For React, The most used generator is create-react-app. You get the entire set up as default.

However, for basic set-up, you can follow the below-mentioned steps.

Prerequisite:

  1. Nodejs
  2. npm/npx

Steps:

  1. Create the folder structure as shown below:
  2. Create util.js and add function in src directory
  3. Create a test file in test folder[Name should contain .test.js]
  4. Init npm package and install jest testing framework

Folder structure:

$ mkdir src test//util.js
exports.add = (a, b) => a+b
$ npm init --y
## install jest testing framework
$ npm i --save-dev jest

Add basic tests and re-run:

//util.test.jsconst {add} = require("../")describe("Util.js", () => {    it("should able to add", () =>{ 
expect(add(1,1)).toBe(2)
})
it("should fail to add", () =>{
expect(add(1,1)).toBe(3)
})
})

Run the test case:

Output:

$ npx jest

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/javascript

Java: The second most used language is Java. Thanks to a tool like Gradle, The setup has become so simple. Whenever I think about my old time, I still get chills of pain.

Prerequisite:

  1. Java
  2. Gradle[v5.5.1 and above]

Steps:

  1. Create a folder, run below command and follow instruction

Once you run gradle init, Select options respectively:

3. library -> 3. java -> 1. Groovy -> 1 Junit 4 <-| Enter <-| Enter

## Create lib using gradle$ md java_code$ gradle init##  --> 3: library 
--> 3: Java
--> 1: Groovy
--> 1: JUnit 4
--> enter <-|
--> enter <-|

Running test:

## run test case
$ ./gradlew test

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/java_code

Python: I have used python as a scripting language. I never get a chance to use python as a full-featured language. While setting up, It was very tough for me to set up the test for a simple function. Till now, Still, I don’t know a proper framework to set up. But I managed to run a few basic test cases.

Prerequisite:

  1. Python[3.6 and above]
  2. Pip[19.3.1 and above]

Steps:

  1. Create a folder and add source code. add util.py and test_util.py
$ md project && md project/src && cd $_$ vi util.py// util.py
def add(a, b):
return a+b
$ vi test_util.py// test_util.py
import util
def test_answer():
assert util.add(1,1) == 2
def test_answerFail():
assert util.add(1,1) == 3

2. Install pytest module using pip

$ pip install -U pytest

3. Run the test case

$ pytest -q src/test_util.py

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/python

Rust: Recently I have started programming on Rust. It is a powerful language and at the same time very simple. Unlike java, C, C++ You do not need much ceremony. I like it a lot. Cargo makes everything easy.

Prerequisite:

  1. Rust
  2. Cargo

Steps:

  1. Create lib using cargo
  2. Write test code in the same file
  3. Run test case
## Create lib using cargo
$ cargo new rust_lang --lib
// src/lib.rs
mod util {
pub fn add(a:i32, b:i32) -> i32 {
a+b
}
}
// test code in same file#[cfg(test)]mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(util::add(1,1), 2);
}
#[test]
fn it_will_works() {
assert_eq!(util::add(1,1), 3);
}
}

Run test case:

$ cargo test -- --nocapture

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/rust_lang

Go-lang: Go is among the most used languages. I have done a few POCs in GoLang. As I mentioned, while doing POCs I avoid (don’t) writing test cases. However, I tried. Setting a test environment was very painful for me. Even setting GOPATH is confusing. However, I managed to do so. Here are the following steps you can follow.

Steps:

  1. Create folder util/ and test/
  2. Copy folder to go path module
  3. Run test case
## Create folder util/ and test/// util/lib.gopackage util 
/// Test function Add
func Add(a int, b int) int {
return a + b
}
//test/lib_test.go
package test
import (
"testing"
util "github.com/xdeepakv/go_lang/util"
)
func TestAddPass(t *testing.T) {
got := util.Add(1, 1)
if got != 2 {
t.Errorf("Add not working properly")
}
}
func TestAddFail(t *testing.T) {
got := util.Add(1, 2)
if got != 2 {
t.Errorf("Add not working properly")
}
}

Try1

cd go_lang
go test -v ./test/

Check Go path, Copy the folder to go path module

## Check go path$ echo $GOPATH## Default would be ~/go
## Copy folder to go path module
$ cp -R ../go_lang $GOPATH/src/github.com/xdeepakv
$ cd $GOPATH/src/github.com/xdeepakv/go_lang

Run the test case:

$ go test -v ./test/

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/go_lang

Updated: 13 Nov.

Swift: Creating a swift library is easy with the swift package manager. However, To write a test case was a challenge for me. I never used XCTest. So I had difficulties to find the correct way. To create a util library you can follow the below steps:

Prerequisite:

  1. Swift 5.1+

Steps:

  1. Create lib using swift package
  2. Tests/utilTests/utilTests.swift
## Create lib using swift package$ md util && swift package init --type library
// util/util.swift
public class Util {
public class func add(_ a: Int, _ b: Int) -> Int {
return a+b
}
}
// Tests/utilTests/utilTests.swift
func testExample() {
XCTAssertEqual(Util.add(1,2), 2)
}

Run the test case:

$ swift test

More: https://github.com/deepakshrma/unit-test--setup-in-all-languages/tree/master/swift_code

Better Example: https://medium.com/quick-code/lets-build-a-command-line-app-in-swift-328ce274f1cc

I am still learning some other languages. I will update the steps for those languages later. If your programming language is not here, please do let me know. I am still working on to find the best way to write unit testing. If you have any suggestions, let me know.

#Cheers #KeepCoding

All the source code can be found on Github:

--

--

Deepak Vishwakarma
Geek Culture

I am a polyglot Blockchain Developer. Mainly work on JavaScript and Nodejs. I work for a multinational Bank as Tech Lead to define the best architecture.