[英]java - How to use Assert.assertEquals when sometimes a String is returned and sometimes null is returned
This is my first question on StackOverflow and I'm a complete beginner so I apologize if my question is vague 这是我关于StackOverflow的第一个问题,我是一个完整的初学者,因此,如果我的问题含糊不清,我深表歉意
I have a method that will sometimes return a String and sometimes return null. 我有一个方法,有时会返回字符串,有时会返回null。
public String confirmLogo() {
String logo = null;
if(sql.getLogo(ID).equals("Qwerty Logo")
logo += "Qwerty Logo";
return logo;
}
So sometimes "qwerty logo" will be returned and sometimes it will return null. 因此,有时会返回“ qwerty徽标”,有时会返回null。
Then in a test class, I'm trying to confirm that whats returned matched whats expected. 然后在测试课程中,我试图确认返回的内容与预期的内容相符。
String primaryLogo = getLogoName(ID);
Assert.assert.equals(primaryLogo, example.confirmLogo());
I'm understandably getting NPEs (java.lang.NullPointerException) returned but I was wondering how I can accomplish this or if someone can't point me to an appropriate reference. 可以理解,我正在返回NPE(java.lang.NullPointerException),但是我想知道如何实现此目标,或者是否有人无法将我指向适当的参考。
Your test should be predictable I would use two different tests to test this, one that expects null
and one that doesn't. 您的测试应该是可预测的,我将使用两种不同的测试来进行测试,一种期望为
null
而另一种则不。 Use different input parameters to achieve the desired behavior (eg once provide x = "test"
, and in other use x = "other"
). 使用不同的输入参数来实现所需的行为(例如,一次提供
x = "test"
,另一种使用x = "other"
)。
Unless you really have eg a Math.random()
in the method :) 除非您的方法中确实包含例如
Math.random()
:
According to the JavaDoc of Assert.assertEquals()
( http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals(java.lang.Object,%20java.lang.Object) ) 根据
Assert.assertEquals()
的JavaDoc( http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals ( Assert.assertEquals()
,% Assert.assertEquals()
) )
Asserts that two objects are equal.
断言两个对象相等。 If they are not, an AssertionError without a message is thrown.
如果不是,则抛出一条不带消息的AssertionError。 If expected and actual are null, they are considered equal .
如果期望值和实际值均为null,则将它们视为相等 。
you should never get a NullPointerException
from calling Assert.assertEquals()
. 永远不要通过调用
Assert.assertEquals()
获得NullPointerException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.