JUnit Assert.assertNotNull()方法示例

x33g5p2x  于2022-10-06 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(569)

JUnit 4教程

assertNotNull() method属于JUnit 4 org.junit.Assert class。在JUnit 5中,所有JUnit 4的断言方法都被移到org.junit.jupiter.api.Assertions类。

何时使用assertNotNull()方法或断言

当我们想断言一个对象不是空的时候,我们可以使用assertNotNull断言。

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

断言一个对象不是空的。如果它是空的,会抛出一个断言错误。 

参数。

  • object - 要检查的对象或null

Assert.assertNotNull(Object object) 方法示例

当我们想断言一个对象不是空时,我们可以使用assertNotNull断言。

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);
      }
   }
}

输出

相关文章