How to know if your Unit Test is “right-sized”?

2019-08-02 18:54发布

One thing that I've always noticed with my unit tests is that they get to be kind of verbose; seeing as they could also be not verbose enough, how do you get a sense of when your unit tests are the right size?

I know of a good quote for this and it's:

"Perfection is achieved, not when there is nothing left to add, but when there is nothing left to remove." - Antoine de Saint-Exupery.

3条回答
Explosion°爆炸
2楼-- · 2019-08-02 19:18

I know a unit test is done when one thing changing in the code could cause the test to fail. If it's testing too many things, that might be good right now, but doesn't help me in the future when I run the test again. I want a failing test to point me right to the thing that caused the failure, not a whole list of possibilities.

查看更多
做自己的国王
3楼-- · 2019-08-02 19:22

One reason why them become verbose is that they're testing multiple things. I try to make each unit test test one thing, and one thing only. So I end up with a lot of tests, each asserting one piece of functionality. It works well since a failure won't disguise another failure by bailing out of the unit test before other assertions are made.

Writing fine-grained tests like this means that if you're not careful, you'll duplicate a lot of setup/teardown code, and that's the stuff you need to spend time on, abstracting it out (in whatever way is suitable).

查看更多
疯言疯语
4楼-- · 2019-08-02 19:24

I've never worried too much about the unit tests being really clean, short and concise code. Sometimes I have 100 line functions which are lots of copy and paste in unit tests, and I don't see that as too large a problem considering most unit tests are setting up some dummy data, and then testing for the correct results based on that.

However, I would say I know I have enough unit tests when I can't think of a single thing in the code which could be wrong.

Edit In response to your edit: I don't look for perfection in unit tests.

查看更多
登录 后发表回答