java - JUnit 测试断言

标签 java junit

我需要为以下代码构建 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 PreconditionsApache 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 检查失败时抛出 NullPointerExceptionIllegalArgumentException,因为 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/

相关文章:

eclipse - 如何使用 eclipse-plugin 打包将 Mockito 添加到 Tycho 单元测试中的测试类路径

java - 运行扩展 HTTPServlet 的简单类时出现 404 错误

java - 捕获上层方法中最深层调用抛出的异常

java - 在加载时要在属性文件中放入哪些值才能获取 IOException?

c - 嵌入式系统到 Web 输出的 Unity 测试

java - org.mockito.exceptions.base.MockitoException : Please ensure that the type 'UserRestService' has a no-arg constructor

java - 如何在 Libgdx 中渲染多个形状?

java - 为什么我使用 datainputstream、java、android 时会得到 0kb 文件?

java - 没有 fromJson 和 toJson 方法的 openapi codegen

Android org.json.JSONObject 在单元测试中返回 null