首页 > 其他分享 >XUnit —— Record.Exception —— Stop Using Assert.Throws in Your BDD Unit Tests

XUnit —— Record.Exception —— Stop Using Assert.Throws in Your BDD Unit Tests

时间:2023-05-08 11:35:17浏览次数:51  
标签:BDD Exception Stop exception method Assert using input Throws

原文:https://www.richard-banks.org/2015/07/stop-using-assertthrows-in-your-bdd.html

Stop Using Assert.Throws in Your BDD Unit Tests

 

I’m sure we’ve all seen the Assert.Throws assertion in test code by now, but just in case you haven’t, here's a simple example:

?
1 2 3 4 5 6 [Test] public void InsertTestNameHere() {     var input = "a string";     Assert.Throws<FormatException>(() => int.Parse(input)); }

If we consider this from an Arrange-Act-Assert (AAA) perspective it’s pretty easy to see that the Act and Assert logic are in a single line. It’s a very common pattern. It works, it works well, and the readability is fine, but if we start using a BDD approach to our unit testing (e.g. with SpecFlow) or we want to explicitly keep the Arrange, Act and Assert sections of our test code separated then Assert.Throws gets in the way.
To fix this we need a way of catching the exception and treating it like a normal object. In NUnit, the Assert.Catch method is for just this purpose. Here’s the adjusted code (using NUnit)

?
1 2 3 4 5 6 7 [Test] public void InsertTestNameHere() {     var input = "a string";     var exception = Assert.Catch(() => int.Parse(input));     Assert.IsInstanceOf<FormatException>(exception); }

In this case we’re catching any exception that int.Parse might throw. If we were more explicit and used Assert.Catch<FormatException>(), NUnit’s behaviour becomes much the same as Assert.Throws, and the test fails immediately if the expected exception isn’t detected. This isn't a behaviour we want, which is why we're using the generalised catch method. Now, since we have our exception in a variable, we can check if it’s the one we expected.
Oh, I forgot to mention it, but if no exception is thrown, Assert.Catch() fails the test immediately. It is an assertion after all. I’m sort of OK with this… but not really, as we’re still mixing assertions and actions on the same line and haven't resolved my original complaint.
For this reason I prefer XUnit’s approach.

?
1 2 3 4 5 6 7 8 [Fact] public void InsertTestNameHere() {     var input = "a string";     var exception = Record.Exception(() => int.Parse(input));     Assert.NotNull(exception);     Assert.IsType<FormatException>(exception); }

The Record.Exception() method won't fail the test, regardless of what happens in the method. Unlike the NUnit approach, it merely records any exception arising from the call or returns null if no exception was thrown. Personally, I feel this approach is a better way to write tests around exceptions while still remaining consistent with the AAA approach. It also works well when using a BDD testing framework that separates the given/when/then step implementations as you can pass the result of the “when” method to the “then” methods with ease.

 

标签:BDD,Exception,Stop,exception,method,Assert,using,input,Throws
From: https://www.cnblogs.com/panpanwelcome/p/17381218.html

相关文章

  • java.io.FileNotFoundException: class path resource [bean.xml] cannot be opened b
    出现这个报错Exceptioninthread"main"org.springframework.beans.factory.BeanDefinitionStoreException:IOExceptionparsingXMLdocumentfromclasspathresource[bean.xml];nestedexceptionisjava.io.FileNotFoundException:classpathresource[bean.......
  • 通过IIS设置来解决System.BadImageFormatException错误
    工作时换了新电脑,然后运行发布后MVC程序就报错:    直接运行Code是OK。错误的原因肯定是64位系统调用了32bit的dll。尝试修改project的Targe为x86,还是无法解决问题。最后查看资料,将应用程序池修改为启用32bit就可以了。 ......
  • java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/
    Java使用AES/CBC/PKCS7Padding加解密时会报错,因为原生JDK不支持。1.在jdk中的jre\lib\security修改java.security文件,替换security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider2./jdk/jre/lib/ext下添加jar包bcprov-jdk15on-1.58.jar ......
  • FAQ-virtualbox安装centOS7 报错 not syncing fatal exception
    1、假设你的虚拟机的名字为:CentOS7提示:已经建完(未启动)2、在命令行窗户执行:VBoxManagemodifyvmCentOS7--spec-ctrlonVBoxManage命令所在的目录为:c:\ProgramFiles\Oracle\VirtualBox>3、启动CentOS7......
  • 经验分享,解决错误:org.apache.ibatis.binding.BindingException
    问题描述:今天在学习mybatis的时候出现了错误:Exceptioninthread"main"org.apache.ibatis.binding.BindingException:Typeinterfacecom.wxy.dao.UserMapperisnotknowntotheMapperRegistry.atorg.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.ja......
  • java.Tang.CassNotFoundException javax.xmL.bind.DatatypeConverter
    报错如下图所示:故障原因:JAXBAPI是javaEE的API,因此在javaSE9.0中不再包含这个Jar包。java9中引入了模块的概念,默认情况下,JavaSE中将不再包含javaEE的Jar包而在java6/7/8时关于这个API都是捆绑在一起的解决方案:降低JDK版本到JDK8手动加入这些依赖......
  • django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.3 or newer is requi
     1、在项目中__init__.py中这个报错原因,python3.5以上版本不支持这种方式frompymysqlimportinstall_as_MySQLdbinstall_as_MySQLdb()解决:importpymysqlpymysql.version_info=(1,4,3,"final",0)#指定了pymysql的版本:1.4.3,按照你版本修改pymysql.install_as_MySQLdb()......
  • Mapreduce二次排序时,将jar包上传至Hadoop上运行时,抛出异常"java.util.NoSuchElementEx
    查询原因后发现是java中实现实现Mapper时StringTokenizer类时使用了一个方法nextToken()会抛出这个异常,”我们可以使用hasMoreTokens()和hasMoreElements()方法来避免异常。如果标记器的字符串中有更多标记可用,则这两种方法都返回true。只有当hasMoreTokens()方法返回Tr......
  • android5.0使用Notification报RemoteServiceException的解决办法
    有时android5.0下使用Notification会报如下错误信息(比如开启重启动系统就要发送通知)android.app.RemoteServiceException:Badnotificationpostedfrompackage*:Couldn'tcreateicon:StatusBarIcon这个问题多数集中在setSmallIcon(R.drawable.scan......
  • C# AggreateException
    在C#中,AggregateException是一种特殊类型的异常,它允许在多个异步任务中捕获并组合多个异常。当在一个异步任务中同时执行多个子任务时,如果其中任何一个子任务抛出了异常,那么父任务将会收到AggregateException异常,它包含一个或多个内部异常,每个内部异常代表一个子任务抛出的异......