适当使用断言 [英] Appropriate use of assert

查看:81
本文介绍了适当使用断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否帮助我更好地理解,断言"与引发异常"的适当用法是什么?每种情况何时合适?

Can you please help me better understand, what is an appropriate use of "assert" vs "throwing an exception? When is each scenario appropriate?

场景1

CODE

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

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (IllegalArgumentException e) {
      assertNotNull(e);
  }
}

场景2

CODE

public Context(Algorythm algo) {
  assert (algo != null);
  this.algo = algo;
}

测试

public void testContext_null() {
  try {
      context = new Context(null);
      fail();
  } catch (AssertionFailedError e) {
      assertNotNull(e);
  }
}

推荐答案

与assert的主要区别是;

The main difference with assert is;

  • 按类/软件包打开/关闭所选测试的功能.
  • 引发的错误.

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

assert is more approriate for tests which will be turned off in production.

如果您希望每次都进行一次检查,特别是如果要验证输入中的数据,则应该使用每次都运行的检查.

If you want a test which is checked every time, esp if validating data from an input, you should use the check which runs every time.

这篇关于适当使用断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆