如何改进我的 junit 测试 [英] How can I improve my junit tests

查看:22
本文介绍了如何改进我的 junit 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没错,我的 junit 测试看起来很长:

Right my junit tests look like a long story:

  • 我创建了 4 个用户
  • 我删除了 1 个用户
  • 我尝试使用已删除的用户登录并确保它失败
  • 我使用剩余的 3 个用户之一登录并验证我可以登录
  • 我从一个用户向另一个用户发送消息,并验证它是否出现在发件人的发件箱和收件人的收件箱中.
  • 我删除了这条消息
  • ...
  • ...

优势:这些测试非常有效(非常擅长检测错误)并且非常稳定,因为它们只使用 API,如果我重构代码,那么测试也会被重构.由于我不使用肮脏的技巧",例如在给定状态下保存和重新加载数据库,因此我的测试无视架构更改和实现更改.

Advantages: The tests are quite effective (are very good at detecting bugs) and are very stable, becuase they only use the API, if I refactor the code then the tests are refactored too. As I don't use "dirty tricks" such as saving and reloading the db in a given state, my tests are oblivious to schema changes and implementation changes.

缺点:测试变得难以维护,测试中的任何更改都会影响其他测试.测试运行 8-9 分钟,这对于持续集成来说非常有用,但对开发人员来说有点令人沮丧.测试不能孤立运行,您能做的最好的事情是在您感兴趣的测试运行后停止 - 但您绝对必须运行之前的所有测试.

Disadvantages: The tests are getting difficult to maintain, any change in a test affects other tests. The tests run 8-9 min which is great for continuous integration but is a bit frustrating for developers. Tests cannot be run isolated, the best you can do is to stop after the test you are interested in has run - but you absolutely must run all the tests that come before.

你会如何改进我的测试?

How would you go about improving my tests?

推荐答案

单元测试应该——理想情况下——是独立的,并且能够以任何顺序运行.所以,我建议你:

unit tests should - ideally - be independent, and able to run in any order. So, I would suggest that you:

  • 分解你的测试以保持独立
  • 考虑使用内存数据库作为测试的后端
  • 考虑将每个测试或套件包装在最后回滚的事务中
  • 分析单元测试以了解时间流向,并专注于此

如果创建几个用户并发送几条消息需要 8 分钟,则性能问题可能不在测试中,而这可能是系统本身的性能问题的征兆——只有您的分析器才能确定!

if it takes 8 minutes to create a few users and send a few messages, the performance problem may not be in the tests, rather this may be a symptom of performance problems with the system itself - only your profiler knows for sure!

[警告:我不认为这些类型的测试是集成测试",尽管我可能是少数;我认为这些类型的测试是功能的单元测试,一种 TDD]

[caveat: i do NOT consider these kinds of tests to be 'integration tests', though i may be in the minority; i consider these kinds of tests to be unit tests of features, a la TDD]

这篇关于如何改进我的 junit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆