Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Humble Object Patternな話

Avatar for いも いも
February 21, 2019

Humble Object Patternな話

Roppongi.unity #01の資料です

Avatar for いも

いも

February 21, 2019
Tweet

More Decks by いも

Other Decks in Programming

Transcript

  1. テストしにくさの元 密結合 static なインスタンス 入力イベントが絡む処理 UI が絡む処理 ファイル、DB などの外部リソー スが絡む処理

    etc.. 実際問題、 どう綺麗に書いてもテストしにくい部分は出てくる Roppongi.unity #1 2019/02/21
  2. Humble Object Pattern とは テストしやすいものとしにくいものを住み分ける実装パター ン テストしにくいものの実装をHumble( 控え目) にする 多分初出は

    xUnit Patterns http://xunitpatterns.com/Humble Object.html クリー ンアー キテクチャ本にも載ってたので有名かも Roppongi.unity #1 2019/02/21
  3. public class PlayerUnit : MonoBehaviour { [SerializeField] private float _speed

    = 1F; void Update() { var horizontal = Input.GetAxis("Horizontal"); var vertical = Input.GetAxis("Vertical"); Move(new Vector3(horizontal, vertical)); } private void Move(Vector3 direction) { transform.position += direction * _speed; } } きちんと任意の方向に動くかテストを実装したい Roppongi.unity #1 2019/02/21
  4. public interface IPlayerUnit { float Speed { get; } Vector3

    Position { get; set; } } // MonoBehavior 成分を0にしたけど、 移動ロジックを持つクラス public class PlayerUnitController { private readonly IPlayerUnit _unit; public PlayerUnitController(IPlayerUnit unit) { _unit = unit; } public void Move(Vector3 direction) { _unit.Position += direction * _unit.Speed; } } テストを書きにくいMonobehavior からロジックを抽出する Roppongi.unity #1 2019/02/21
  5. public class PlayerUnitHumble : MonoBehaviour, IPlayerUnit { [SerializeField] private float

    _speed = 1F; private PlayerUnitController _controller; public float Speed => _speed; public Vector3 Position { get => transform.position; set => transform.position = value; } void Start() => _controller = new PlayerUnitController(this); void Update() { var horizontal = Input.GetAxis("Horizontal"); var vertical = Input.GetAxis("Vertical"); _controller.Move(new Vector3(horizontal, vertical)); } } Roppongi.unity #1 2019/02/21
  6. テストコー ド public class PlayerUnitTest { // テスト用のいい感じモック public class

    MockPlayerUnit : IPlayerUnit { public float Speed { get; set; } public Vector3 Position { get; set; } } [Test] public void PlayerUnitMove() { var unit = new MockPlayerUnit { Speed = 5, Position = Vector3.zero }; var controller = new PlayerUnitController(unit); controller.Move(Vector3.up); Assert.AreEqual(new Vector3(0,5F,0), unit.Position); } } Roppongi.unity #1 2019/02/21