# Django 官方提出的关于测试代码过多的建议

翻官方文档的时候看到的,感觉不错,收藏一下

# 汉语

# 当需要测试的时候,测试用例越多越好

貌似我们的测试多的快要失去控制了。按照这样发展下去,测试代码就要变得比应用的实际代码还要多了。而且测试代码大多都是重复且不优雅的,特别是在和业务代码比起来的时候,这种感觉更加明显。

但是这没关系! 就让测试代码继续肆意增长吧。大部分情况下,你写完一个测试之后就可以忘掉它了。在你继续开发的过程中,它会一直默默无闻地为你做贡献的。

但有时测试也需要更新。想象一下如果我们修改了视图,只显示有选项的那些投票,那么只前写的很多测试就都会失败。但这也明确地告诉了我们哪些测试需要被更新,所以测试也会测试自己。

最坏的情况是,当你继续开发的时候,发现之前的一些测试现在看来是多余的。但是这也不是什么问题,多做些测试也 不错。

如果你对测试有个整体规划,那么它们就几乎不会变得混乱。下面有几条好的建议:

  • 对于每个模型和视图都建立单独的 TestClass
  • 每个测试方法只测试一个功能
  • 给每个测试方法起个能描述其功能的名字

# English

# When testing, more is better

It might seem that our tests are growing out of control. At this rate there will soon be more code in our tests than in our application, and the repetition is unaesthetic, compared to the elegant conciseness of the rest of our code.

It doesn't matter. Let them grow. For the most part, you can write a test once and then forget about it. It will continue performing its useful function as you continue to develop your program.

Sometimes tests will need to be updated. Suppose that we amend our views so that only Questions with Choices are published. In that case, many of our existing tests will fail - telling us exactly which tests need to be amended to bring them up to date, so to that extent tests help look after themselves.

At worst, as you continue developing, you might find that you have some tests that are now redundant. Even that's not a problem; in testing redundancy is a good thing.

As long as your tests are sensibly arranged, they won't become unmanageable. Good rules-of-thumb include having:

  • a separate TestClass for each model or view
  • a separate test method for each set of conditions you want to test
  • test method names that describe their function