适当使用断言

Jam*_*sev 2 java junit assert

能帮助我更好地理解,"断言"与"抛出异常"的适当用法是什么?每个场景何时适用?

场景1

public Context(Algorythm algo) {
  if (algo == null) {
      throw new IllegalArgumentException("Failed to initialize Context");
  }
  this.algo = algo;
}
Run Code Online (Sandbox Code Playgroud)

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (IllegalArgumentException e) {
      assertNotNull(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

情景2

public Context(Algorythm algo) {
  assert (algo != null);
  this.algo = algo;
}
Run Code Online (Sandbox Code Playgroud)

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (AssertionFailedError e) {
      assertNotNull(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

与assert的主要区别是;

  • 能够按类/包打开/关闭所选测试.
  • 抛出的错误.

对于将在生产中关闭的测试,断言更加合适.

如果您希望每次都检查一次测试,例如,如果验证来自输入的数据,则应使用每次运行的检查.