平衡设计原则:单元测试 [英] Balancing Design Principles: Unit Testing

查看:135
本文介绍了平衡设计原则:单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Bananagrams的模拟。目前,我有一个 GameMaster 类,用于维护常见的片段集合。 交易(玩家)方法向该玩家发送一定数量的作品。

I am writing a simulation of Bananagrams. Currently, I have a GameMaster class that maintains the common collection of pieces. The deal(Player) method deals a certain number of pieces to that player.

我想编写单元测试为了这。但是,此时,我没有吸气剂,因此无法检查物体的状态。

I want to write unit tests for this. However, at this point, I have no getters, and thus no way to check the status of the objects.

为什么不添加吸气剂?我不想仅为测试添加代码到公共接口。现在,没有其他理由可以公开这些功能。

Why not add getters? I don't want to add code to the public interface only for testing. Right now, there is no other reason to expose those functions.

我应该在这做什么?无论如何添加getter,混乱公共API(或者希望将来需要它们)?放弃单元测试? (听起来不错。)

What am I supposed to do here? Add the getters anyway, cluttering the public API (or hoping that they will be needed in the future)? Forgo unit testing? (Sounds like a bad idea.)

或者,这是否表明我的公共界面存在缺陷?

Or, does this indicate that my public interface is flawed?

推荐答案

不是依赖于播放器的具体实例,而是将单元测试写入接口(或等效的),并依靠模拟或其他交互来验证播放器是否在正确的状态,但只是正确的调用(从GameMaster类的视图。

Instead of relying upon a concrete instance of a Player, write your unit tests to an interface (or the equivalent), and rely upon mocks or other interaction to validate not that the player is in the correct state, but simply that the correct calls (from the view of the GameMaster class.

如果你不能在不依赖验证最终状态的情况下验证GameMaster类的正确行为玩家,这表明你的责任是错误的.GameMaster应该负责告诉玩家发生了什么,而玩家应该负责采取适当的行动。

If you cannot validate correct behavior of the GameMaster class without relying upon validating the end state of the Player, that's a sign that your responsibilities are misplaced. The GameMaster should be responsible for telling the Player what happened, while the Player should be responsible for taking the appropriate action.

这也是一个好处,因为它意味着GameMaster的测试将仅依赖于GameMaster类的行为,如果播放器不需要触及class改变了它的行为。

This is also a benefit, as it means that the tests for the GameMaster will be dependent only on the behavior of the GameMaster class, and will not need to be touched if the Player class changes its behavior.

避免为单元测试添加getter。当您想要添加一个getter时,请改为使用交互测试(如我刚才所述)而不是基于状态的测试。

Avoid adding getters for unit tests. When you're tempted to add a getter, look instead at using interaction testing (as I just described) instead of state-based testing.

这篇关于平衡设计原则:单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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