JUnit Assert.assertNotNull() Method Example

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

assertNotNull() method belongs to JUnit 4 org.junit.Assert class. In JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.

When to use assertNotNull() method or assertion

When we want to assert that an object is not null we can use the assertNotNull assertion.

void org.junit.Assert.assertNotNull(Object object)

Asserts that an object isn't null. If it is an AssertionError is thrown. 
Parameters:
  • object - Object to check or null

Assert.assertNotNull(Object object) Method Example

When we want to assert that an object is not null we can use the assertNotNull assertion:
import static org.junit.Assert.assertNotNull;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;

import com.javaguides.strings.StringUtility;

public class AssertNotNullExample {
    public static String[] toStringArray(final Collection<?> collection) {
        if (collection == null) {
             return null;
        }
       return collection.toArray(new String[collection.size()]);
    }

 @Test
 public void toStringArrayTest() {
      final String[] strArray = StringUtility.toStringArray(Arrays.asList("a", "b", "c"));
      for (final String element : strArray) {
           assertNotNull(element);
      }
   }
}

Output:



Related JUnit Examples

  1. JUnit Assert.assertArrayEquals() Method Example
  2. JUnit Assert.assertEquals() Method Example
  3. JUnit Assert.assertTrue() Method Example
  4. JUnit Assert.assertFalse() Method Example
  5. JUnit Assert.assertNull() Method Example
  6. JUnit Assert.assertNotNull() Method Example
  7. JUnit Assert.assertSame() Method Example
  8. JUnit Assert.assertNotSame() Method Example
  9. JUnit Assert.fail() Method Example

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare