JUnit Assert.assertNull()方法示例

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

JUnit 4教程

在这篇文章中,我们将通过一个例子演示如何使用Assert.assertNull()方法。查看JUnit 5教程和例子,请访问JUnit 5教程在JUnit 5中,所有JUnit 4断言方法都被移到org.junit.jupiter.api.Assertions类。

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

当我们想测试一个对象是否为空时,我们可以使用assertNull断言。

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

断言一个对象是空的。如果它不是,则抛出一个AssertionError。 

参数。

  • object - 要检查的对象或null

Assert.assertNull(Object object) 方法示例

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;

public class AssertNullExample {
 /**
* Concatenate the given {@codeString} arrays into one,
* with overlapping array elements included twice.
* <p>The order of elements in the original arrays is preserved.
* @param array1 the first array (can be {@codenull})
* @param array2 the second array (can be {@codenull})
* @return the new array ({@codenull} if both given arrays were {@codenull})
*/
 
 public static String[] concatenateStringArrays( final String[] array1,  final String[] array2) {
     if (array1 == null || array1.length == 0) {
          return array2;
     }
     if (array2 == null || array2.length == 0) {
          return array1;
     }

     final String[] newArr = new String[array1.length + array2.length];
     System.arraycopy(array1, 0, newArr, 0, array1.length);
     System.arraycopy(array2, 0, newArr, array1.length, array2.length);
     return newArr;
 }
 
 @Test
 public void testConcatenateStringArrays() {
     final String[] input1 = new String[] {"myString2"};
     final String[] input2 = new String[] {"myString1", "myString2"};
     final String[] result = concatenateStringArrays(input1, input2);
  
     assertNull(concatenateStringArrays(null, null));
  
     assertEquals(3, result.length);
     assertEquals("myString2", result[0]);
     assertEquals("myString1", result[1]);
     assertEquals("myString2", result[2]);

     assertArrayEquals(input1, concatenateStringArrays(input1, null));
     assertArrayEquals(input2, concatenateStringArrays(null, input2));  
   }
}

输出

相关文章