Write First JUnit Test

Hey everyone in this article, Let’s write the very first JUnit 5 test case with easy to understanding example.




Read More:

Consider the following example, the method getMovies() will return the empty list.

package in.bushansirgur;

import java.util.Collections;
import java.util.List;

public class Movies {
	
	public List getMovies() {
		return Collections.emptyList();
	}
}

Now we want to write a JUnit test case to test whether the method getMovies() should return an empty list or not

Development Steps


A test case is broken down into the following 3 parts

  • Setup the data that our test case needs
  • Call the method being tested
  • Perform the assertions to verify if the expected behavior is correct

This is also called AAA (Arrange, Act and Assert)

Success Scenario


package in.bushansirgur;

import static org.junit.jupiter.api.Assertions.*;

import java.util.List;

import org.junit.jupiter.api.Test;

class MoviesTest {

	@Test
	void testMovies() {
		Movies m = new Movies();
		List list = m.getMovies();
		assertTrue(list.isEmpty(), () -> "Movies should be empty");
	}

}

@Test annotation indicates that the method is the Junit test case. If you notice that we have used @Test annotation from org.unit.jupiter.api.Test the package. In the earlier versions of JUnit, this annotation was from org.junit.Test the package. So to write JUnit 5 test cases we have to use org.unit.jupiter.api.Test annotation.

JUnit 5 has trimmed down assertions support. There is no assertThat() method in JUnit 5. It is expected that you will use a third-party assertion library like Hamcrest or AssertJ. In the code, we have used the inbuilt assertion assertTrue(), which tests whether the condition is true or not.

Now that run the test case, our test case should pass.

Screenshot-2022-07-04-at-9-00-34-PM

Failure Scenario


Inside the getMovies() method, return null instead of returning the empty list.

package in.bushansirgur;

import java.util.Collections;
import java.util.List;

public class Movies {
	
	public List getMovies() {
		return null;
	}
}

Now that run the test case, our test case should fail

Screenshot-2022-07-04-at-9-01-38-PM

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply