JUNIT ASSERTNOTSame示例
时间:2020-02-23 14:41:31 来源:igfitidea点击:
JUNIT 5的org.junit.jupiter.Assertions类提供了不同的静态断言方法来编写测试用例。
请注意,在JUnit 4或者JUnit 3的情况下,我们需要使用JUnit的org.junit.assert类来使用Assertnull方法来声明。
assertions.assertnotsame()检查预期和实际对象是否参考不同的对象。
如果两者都引用相同的对象,它将通过AsserTerror。
public static void assertNotSame(Object expected,Object actual) public static void assertNotSame(Object expected,Object actual,String message) public static void assertNotSame(Object expected,Object actual,Supplier messageSupplier)
这是一个简单的例子
package org.igi.theitroad; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class AssertNotSameTest { /* * Examples for each overloaded methods of assertNotSame */ //public static void assertNotSame(Object expected, Object actual) @Test public void test1(){ String str1="Apple"; String str2="Apple"; Assertions.assertNotSame(str1,str2); } //public static void assertNotSame(Object expected, Object actual, String message) @Test public void test2(){ String str1=new String("Apple"); String str2=new String("Apple"); Assertions.assertNotSame(str1,str2,"str1 and str2 refer to same object"); } //public static void assertNotSame(Object expected, Object actual, Supplier messageSupplier) @Test public void test3(){ String str1=new String("Apple"); String str2=str1; Assertions.assertNotSame(str1,str2,() -> "str1 and str2 refer to same object"); } }
运行上面的TestCase时,我们将得到以下输出:
让我们了解每个测试用例的输出:
test1 - 失败
由于str1和str2引用相同的字符串文字,此测试用例将失败。
如果我们与此混淆,请参阅串面试问题。
test2 - 通过
作为str1和str2都指的是两个不同的新字符串对象,此测试用例将通过。
test3 - 失败
由于str1引用新对象和str2,请参阅相同的字符串对象(str2 = str1),此测试用例将失败。
这是关于assertions.assertnotsame()方法。