我应该测试正面和负面的陈述吗?

时间:2012-02-02 05:39:59

标签: ruby-on-rails testing tdd

我正在为rails中的简单用户模型编写单元测试,并开始考虑如何编写测试。

似乎有积极的测试:

test "password should match the password_confirmation " do
    user = User.new(
    :email => "email@mail.com",
    :password => "password",
    :password_confirmation => "password")
    assert user.valid?, "did not save user even though password matches confimation"
  end

和否定测试:

test "password should not be valid with mismatching password_confirmation " do
    user = User.new(
    :email => "email@mail.com",
    :password => "password",
    :password_confirmation => "doesnotmatch")
    assert user.invalid?, "saved user with mismatching password_confirmation"
  end

在测试套件中包含这两个测试是否是多余的,还是一个好习惯?

2 个答案:

答案 0 :(得分:1)

查看TDD. When you can move on?,它解释了您准备好测试(和代码)的时间,并可继续前进。在您的示例中,这意味着:

  • 你先写下积极的测试。测试失败。
  • 然后编写必要的代码,以便测试成功。
  • 之后,您需要另一个测试来证明您的实施是不够的。当你写了例如。

    class User
      def initialize(hash)
        @hash = hash
      end
      def valid?
        true
      end
    end
    

    你需要另一个测试用例来证明这是错误的。

  • 编写下一个测试用例,表明检查密码可能会失败。

我看到以下情况:

  • 无密码
  • 匹配密码(但太短)
  • 匹配密码(很长很难)
  • 不匹配密码

所以你需要4个测试用例。

答案 1 :(得分:0)

我想说这是一个好主意,因为知道其中一个测试通过并不意味着另一个测试通过。