c# - 如何先写单元测试后写代码?

标签 c# unit-testing nunit moq

我是单元测试的新手,读过好几次我们应该先写单元测试,然后再写实际代码。截至目前,我正在编写我的方法,然后对代码进行单元测试。

If you write the tests first...

You tend to write the code to fit the tests. This encourages the "simplest thing that solves the problem" type development and keeps you focused on solving the problem not working on meta-problems.

If you write the code first...

You will be tempted to write the tests to fit the code. In effect this is the equivalent of writing the problem to fit your answer, which is kind of backwards and will quite often lead to tests that are of lesser value.

我觉得不错。但是,如何在编写代码之前编写单元测试? 我是按字面意思接受建议吗?这是否意味着我应该准备好我的 POCO 类和接口(interface),然后编写单元测试?

任何人都可以通过一个简单的例子向我解释这是如何完成的,比如将两个数字相加吗?

最佳答案

其实很简单。红色、绿色、重构。

红色表示 - 您的代码已完全损坏。语法高亮显示为红色,测试未通过。为什么?您还没有编写任何代码。

绿色表示 - 您的应用程序已构建且测试通过。您已经添加了所需的代码。

重构意味着 - 清理它并确保测试通过。

您可以像这样编写一个测试:

[TestMethod]
public void Can_Create_MathClass() {
    var math = new MathClass();
    Assert.IsNotNull(math);
}

这将失败(RED)。你如何解决它?创建类。

public class MathClass {
}

就是这样。它现在通过了(绿色)。下一个测试:

[TestMethod]
public void Can_Add_Two_Numbers() {
    var math = new MathClass();
    var result = math.Add(1, 2);
    Assert.AreEqual(3, result);
}

这也失败了(RED)。创建 Add 方法:

public class MathClass {
    public int Add(int a, int b) {
        return a + b;
    }
}

运行测试。这将通过(绿色)。

重构就是清理代码。这也意味着您可以删除多余的测试。我们知道我们现在有 MathClass.. 所以您可以完全删除 Can_Create_MathClass 测试。完成后..您已通过 REFACTOR,可以继续。

请务必记住,重构步骤不仅仅意味着您的普通代码。这也意味着测试。你不能让你的测试随着时间的推移而恶化。您必须将它们包含在重构步骤中。

关于c# - 如何先写单元测试后写代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003983/

相关文章:

c# - 为整个项目全局声明预处理器符号(如 DEBUG)

testing - 在 NUnit [TearDown] 中,如何确定测试是否单独运行?

unit-testing - 需要很多辅助方法来协助我的单元测试类——这正常吗?

c# - 用于选择两个集合之间的公共(public)元素的 Linq 语句

c# - 为什么 JSON 响应中的 HTML 会被编码?

c# - WP7 - 错误 'XmlException was unhandled' 尽管检查文件是否存在

node.js - 如何使用 sinon stub NodeJS "required"构造函数?

unit-testing - Grails 2.5.5 Controller 单元测试无法转换对象错误

c# - 是否有执行一系列超时的模式?

ruby-on-rails - 数据库/模型夹具和原始状态