开发者

Should I open up a class's instance variables just for test validation?

I'm new to BDD, and I'm finding alot of instances where I'm adding instance variables to attr_accessor only so that my tests have an easy way to validate whether they are in the state that they should be in. But this feels a little dirty because no other class needs this information, and so I'm only making it public for the tests开发者_开发知识库. Is this standard or a sign of bad design?

For example I have a collection class which stores an object, and then commits it to a batch array. At the end of the import, the batch array is used to make a batch insert into the database. But there is no need to check on the state of the batch at any point. But in testing I'm wanting to make sure that the batch is in the state that I think it is, and so am opening up that variable for inspection. Is the fact that it's not being checked within the code the real problem?


Is using instance_variable_get an option for you?

>> class Foo
..   def initialize
..     @foo = 'bar'
..     end
..   end #=> nil
>> Foo.new.instance_variable_get(:@foo) #=> "bar"


DON'T Do That!

This is going too deep. See the comments from @Andy and @Michael in the thread on the other 'accepted' answer

Don't write unit tests that look inside the code unit. If it's not something you can see from the external interfaces to the object then it doesn't need to be unit tested. You are going past how the code behaves into how it implements that behavior, and you don't want tests that go down to that level as they don't provide any real value in terms of proving that the code does what it should.

Just consider how many tests you might have to update if someone re-factors that code and in order to make it more readable changes the internal names of things.. or maybe finds a better way of doing whatever and all the instance variables get altered.. The code unit could still be working perfectly fine, but the unit tests would fail..

Alternatively if a change was made that adjusts how the internal variables report out to the interface, the code could effectively be broken, but the tests that are looking at the internal values of the instance variables would not report any failure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜