Core Javajunit

JUnit assertTrue example

1. Introduction

Every developer on every platform should always have a solid JUnit test case to secure the changes they made. This will minimise the potential risk of negativity to an existing system. There are a lot of ways to do JUnit Testing and a lot of functions available to do them. One of the most popular Unit Testing framework is the JUnit Library.

In this post, I’ll be discussing the usage of JUnit assertTrue and how can a developer use this to evaluate the test cases of their source using the assertTrue method from the Assert class object.
 
 
 

2. The Source

The source code below shows how can we use the assertTrue function.

JUnitTestAssertions.java

package com.areyes1.junitassertrue.sample;
package com.areyes1.junitassertrue.sample;

import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

public class JUnitTestAssertions {
	
	int totalNumberOfApplicants = 0;
	int totalNumberOfAcceptableApplicants = 10;
	
	@Before
	public void setData(){
		this.totalNumberOfApplicants = 9;
	}
	
	@Test
	public void testAssertions() {
		assertTrue((this.totalNumberOfApplicants != this.totalNumberOfAcceptableApplicants));
	}
	
	@Test
	public void testAssertFalse() {
		assertTrue((this.totalNumberOfApplicants == this.totalNumberOfAcceptableApplicants));
	}
	
	@Test
	public void testAssertTrueWithMessage(){
		assertTrue("Is total number of applicants acceptable?",(this.totalNumberOfApplicants != this.totalNumberOfAcceptableApplicants));
	}
}

The assertTrue is a function from the Assert object of the JUnit Library. It can be used to evaluate a specific condition that that runs on your application. This can be a simple boolean output if the user exist or not, an account has enough cash for a transaction or, in this case, a check if the number of applicants is within the acceptable range.

Running this example will give you an output in Eclipse.

Figure 1.0 JUnit Test result ran in Eclipse
Figure 1.0 JUnit Test result ran in Eclipse

3. Download the Eclipse project

This was an example of JUnit assertTrue.

Download
You can download the full source code of this example here : junit-asserttrue-example

Alvin Reyes

Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button