Writing “unit testable” code?

2019-01-16 04:02发布

What kind of practices do you use to make your code more unit testing friendly?

19条回答
祖国的老花朵
2楼-- · 2019-01-16 04:42

Write the tests first - that way, the tests drive your design.

查看更多
放我归山
3楼-- · 2019-01-16 04:42

I'm sure I'll be down voted for this, but I'm going to voice the opinion anyway :)

While many of the suggestions here have been good, I think it needs to be tempered a bit. The goal is to write more robust software that is changeable and maintainable.

The goal is not to have code that is unit testable. There's a lot of effort put into making code more "testable" despite the fact that testable code is not the goal. It sounds really nice and I'm sure it gives people the warm fuzzies, but the truth is all of those techniques, frameworks, tests, etc, come at a cost.

They cost time in training, maintenance, productivity overhead, etc. Sometimes it's worth it, sometimes it isn't, but you should never put the blinders on and charge ahead with making your code more "testable".

查看更多
Deceive 欺骗
4楼-- · 2019-01-16 04:43
  1. Use TDD
  2. When writing you code, utilise dependency injection wherever possible
  3. Program to interfaces, not concrete classes, so you can substitute mock implementations.
查看更多
迷人小祖宗
5楼-- · 2019-01-16 04:43

When writing tests (as with any other software task) Don't Repeat Yourself (DRY principle). If you have test data that is useful for more then one test then put it someplace where both tests can use it. Don't copy the code into both tests. I know this seems obvious but I see it happen all the time.

查看更多
闹够了就滚
6楼-- · 2019-01-16 04:45

No Statics - you can't mock out statics.

Also google has a tool that will measure the testability of your code...

查看更多
神经病院院长
7楼-- · 2019-01-16 04:46

Small, highly cohesive methods. I learn it the hard way. Imagine you have a public method that handles authentication. Maybe you did TDD, but if the method is big, it will be hard to debug. Instead, if that #authenticate method does stuff in a more pseudo-codish kind of way, calling other small methods (maybe protected), when a bug shows up, it's easy to write new tests for those small methods and find the faulty one.

查看更多
登录 后发表回答