Lambda 函数简化单元测试?
我有一个 Sport 类定义为:
Sport:
- name
- other fields
我有一个测试,我想验证添加运动“橄榄球”是否包含在 sport_objects 列表中。
目前,测试很脆弱,检查我知道它所在的索引处的对象名称:
self.assertEquals('rugby', sports_objects[3].name)
我想将其更改为 self.assertIn() ,这样测试就不会那么脆弱,并且不会受到影响索引更改(因为我不关心这里的顺序)。
有没有办法在不依赖索引的情况下改变它(使用 lambda 函数?)?
编辑:
这两个答案都很好用。我有多个断言语句,所以我的最终解决方案是:
sports_names = [i.name for i in sports_objects]
self.assertIn('rugby', sports_names)
self.assertIn('baseball', sports_names)
I have an Sport class defined as:
Sport:
- name
- other fields
I have a test where I want to verify that adding the sport 'rugby' is contained in the list of sport_objects.
Currently, the test is brittle, checking the name of the object at the index I know it's at:
self.assertEquals('rugby', sports_objects[3].name)
I'd like to change this to self.assertIn() so the test isn't as brittle and won't be affected if the index changes (since I don't care about the order here).
Is there a way to change this (using a lambda function?) without relying on the index?
Edit:
Both answers given work great. I have multiple assert statements, so my final solution is:
sports_names = [i.name for i in sports_objects]
self.assertIn('rugby', sports_names)
self.assertIn('baseball', sports_names)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你总是可以这样做:
或者类似的事情
You can always do:
or something like