我需要为以下代码构建 Junit 测试用例,并且我正在尝试让其中一个测试测试 assert s1 != null : "Violation of: s1 is not null";
、 assert s2 != null : "违反:s2 不为 null";
和 assert s1.length() >= 1 : "|s1| >= 1";
当传递空序列或 s1
的长度 >= 1 时,code> 语句会给出错误。
我不知道执行此操作的确切方法。
几个论坛建议使用“Try Catch”,但我不知道它到底是如何工作的。
如有任何帮助,我们将不胜感激!
public static void itersmooth(Sequence<Integer> s1, Sequence<Integer>
s2){
assert s1 != null : "Violation of: s1 is not null";
assert s2 != null : "Violation of: s2 is not null";
assert s1.length() >= 1 : "|s1| >= 1";
s2.clear();
if (s1.length() > 1){
int inp1 = 1;
for (int inp2 = 0; inp2 < (s1.length() - 1); inp2++){
int valone = s1.remove(inp2);
int valtwo = s1.remove(inp1 - 1);
int valoneT = valone / 2;
int valtwoT = valtwo / 2;
int valtemp = valoneT + valtwoT;
if ((valone % 2 != 0 || valtwo % 2 != 0) && (valone > 0 && valtwo > 0)) {
valtemp++;
}
if ((valone % 2 != 0 || valtwo % 2 != 0) && (valone < 0 && valtwo < 0)){
valtemp--;
}
s2.add(inp2, valtemp);
s1.add(inp2, valone);
s1.add(inp1, valtwo);
inp1++;
}
}
}
最佳答案
我不会使用 Java 的断言来防范 null
引用,主要是因为该功能可以 - and by default is - 关掉。如果您的测试系统启用了断言而您的生产系统没有启用断言,这可能会导致非常难以发现的错误。
相反,我会使用先决条件库,例如 Guava Preconditions或Apache Commons Validate以此目的。除此之外,我会用 "NotNull" annotation 注释方法参数。 ,例如javax.annotation.Nonnull
,以便客户端代码在现代 IDE 中获得编译时保护。
因此,方法签名和保护条件将变成这样(使用 Commons Validate):
import org.apache.commons.lang3.Validate;
import javax.annotation.Nonnull;
//...
public static void itersmooth(@Nonnull Sequence<Integer> s1,
@Nonnull Sequence<Integer> s2) {
Validate.notNull(s1, "Violation of: s1 is not null");
Validate.notNull(s2, "Violation of: s2 is not null");
Validate.isTrue(s1.length() >= 1, "|s1| >= 1");
// ...
}
进行此更改后,编写单元测试变得很简单,因为该方法保证在 notNull
检查失败时抛出 NullPointerException
或 IllegalArgumentException
,因为 isTrue
检查失败;您无需担心断言是否启用。
用于检查传入的第一个参数不能为 null
的示例测试如下所示:
@Test(expected=NullPointerException.class)
public void throwsWhenFirstSequenceIsNull() {
MyClass.itersmooth(null, new Sequence<Integer>(1,2,3));
Assert.fail("Null argument didn't cause an exception!");
}
关于java - JUnit 测试断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43926345/