【发布时间】:2014-10-02 23:07:50
【问题描述】:
我从使用 Minitest 的 Ruby 应用程序中的 DDD 和 TDD 开始。 我创建了一个存储库类(没有数据库访问权限,但它为我生成了实体)。这是一个单例。
我想测试实体的生成。问题是因为是单例,所以测试的执行顺序会影响结果。
有没有办法强制处理单例元素,使其“新鲜”?
这是我的存储库代码:
require "singleton"
class ParticipantRepository
include Singleton
def initialize()
@name_count = 0
end
def generate_participant()
participant = Participant.new
participant.name = "Employee#{get_name_count()}"
return participant
end
private
def get_name_count()
old_name_count = @name_count
@name_count += 1
return old_name_count
end
end
还有测试:
require_relative 'test_helper'
class ParticipantRepositoryTest < MiniTest::Unit::TestCase
def setup()
@repository = ParticipantRepository.instance
end
def test_retrieve_participant
participant = @repository.generate_participant
refute_nil participant
refute_nil participant.name
refute_equal("", participant.name)
assert_equal(0, participant.subordinates_count)
end
def test_employee_name_increment
participant1 = @repository.generate_participant
participant2 = @repository.generate_participant
refute_equal(participant1.name, participant2.name)
index_participant1 = /Employee([0-9]+)/.match(participant1.name)[1]
index_participant2 = /Employee([0-9]+)/.match(participant2.name)[1]
assert_equal(0, index_participant1.to_i)
assert_equal(1, index_participant2.to_i)
end
end
断言assert_equal(0, index_participant1.to_i)先执行test_employee_name_increment成功,最后执行失败。
我希望能够测试存储库(因为它会演变成更大的东西)。我该怎么做?
谢谢!
【问题讨论】:
-
单例和可测试性经常不一致。考虑使用某种 DI 来强制执行单例,而不是让班级担心这一点。
-
@MattBall 这会很棒。你有任何关于如何使用 DI 来解决这个问题的参考吗?
-
没什么特别的;我不写Ruby。看一看:stackoverflow.com/search?q=ruby+dependency+injection
-
看看我对类似问题的回答 - stackoverflow.com/a/23901644/633234