How to write unit tests

widget

Unit tests are an essential part of software development that independently test​ a part of the app. Unit testing works in three steps, also known as AAA (Arrange, Act, Assert):

  1. It initializes the part of the code that needs to be tested.
  2. It applies some stimulus to the system under observation.
  3. It records and observes the results.

A unit test can check multiple behaviors of a system, but usually, they fall under two categories: state-based and interaction-based. State-based unit testing verifies that the system produces correct results; whereas, interaction-based unit testing makes sure that the system calls the correct methods.

Code

Let’s implement a simple test case. Consider class Name that combines and displays the firstname and lastname that it takes in as a ​parameter.

class Name {
public String conc( String firstname, String lastname ) {
return ("Your name is " + firstname + " " + lastname)
}
}

Now, let’s write a function to test the conc function within the name class:

class Test {
public static void main( String args[] ) {
var my_name = new Name();
String output = my_name.conc("John", "Smith")
if (output != "Your name is John Smith")
throw new InvalidOperationException()
System.out.println( "Passed!" );
}
}

If the test passes, the program gives the output “Passed!” and quits. If the test fails, it throws an exception.

Some programs may be hard to test because of the way they are written. For such programs, the best approach is to perform as many unit tests as possible and then use other techniques.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved