要一个好的单元测试有哪些属性? [英] What attribute should a good Unit-Test have?

查看:116
本文介绍了要一个好的单元测试有哪些属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个单元测试应该


  • 产生确定性的结果

  • 独立

  • 被有效

  • ...

应该测试也有其他什么特点?

What other characteristics should a test also have?

推荐答案

啊。我最喜欢的科目:-)从哪里开始...

Ah. My favorite subject :-) Where to start...

据杰拉德·梅萨罗斯(阅读本书单元测试)

According to xUnit test patterns by Gerard Meszaros (THE book to read about unit testing)


  • 测试应该降低风险,不
    介绍吧。

  • 测试应该很容易运行。

  • 测试应该是易于维护
    系统升级的身边

有些事情要使它更容易些:

Some things to make this easier:


  • 测试只能失败,因为一个
    原因。 (测试只测试一件事,避免多次声称为例。)

  • 应该只有一个测试,对于该原因而失败。 (这让你的testbase维护)

  • 最小化的测试依赖(无
    在数据库,文件,用户界面​​的依赖
    等等。)

其他的事情来看待:

命名

有一个描述性的名称。测试 - 名称应念想规范。如果你的名字太长,你可能测试的太多了。

Naming
Have a descriptive name. Tests-names should read like specifications. If your names get too long you're probably testing too much.

结构

使用AAA结构。这是嘲讽框架新玩意,但我认为这是构建所有测试这样的一个好方法。

Structure
Use AAA structure. This is the new fad for mocking frameworks, But I think it's a good way to structure all your tests like this.

安排您的上下文

法,这样做需要的东西进行
测试
断言,声称要检查什么

Arrange your context
Act, do the things that need to be tested
Assert, assert what you want to check

我通常把我的测试中code三个区块。认识到这一点模式使测试更具有可读性。

I usually divide my tests in three blocks of code. Knowing this pattern makes tests more readable.

嘲弄与存根

当使用模拟框架总是试图诉诸嘲讽前使用存根和基于状态的测试。

Mocks vs. Stubs
When using a mocking framework always try to use stubs and state based testing before resorting to mocking.

存根是站在你想测试对象的依赖对象。您可以程序行为融入其中,他们可以叫你的测试。嘲笑,让你断言,如果他们被称为以及如何扩大这一点。嘲讽是非常强大的,但它可以让你测试执行,而不是pre和你的code的后置条件。这往往使测试更脆。

Stubs are objects that stand in for dependencies of the object you're trying to test. You can program behaviour into them and they can get called in your tests. Mocks expand on that by letting you assert if they were called and how. Mocking is very powerfull but it lets you test implementation instead of pre and post-conditions of your code. This tends to make tests more brittle.

这篇关于要一个好的单元测试有哪些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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