gpt4 book ai didi

JUnit Assert.assertNull()方法示例

转载 作者:知者 更新时间:2024-03-12 12:34:31 25 4
gpt4 key购买 nike

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

输出

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com