2

This is my first question on Stack Overflow, so please forgive me for any poor practices in my question-asking (though I do appreciate feedback to make me better at it.)

I'm currently working on a personal project: a 2D strategy game with minimal graphics. Now that I've completed a very barebones application, I decided to start implementing unit tests (I'm using JUnit) and I quickly realized how painful that will be given my current design.

Consider a few classes from my current design: Ship, ShipWeapon, ShipProvider, and ShipWeaponProvider. A Ship contains a list of ShipWeapons that it can fire at other ships. A ShipWeapon is an object defining certain weapon characteristics (i.e. damage, accuracy, etc.) ShipProvider and ShipWeaponProvider objects are used to load Ship/Weapon definitions from a file so they can be instantiated later (i.e. shipProvider.getShip("dummyShip") returns a new Ship of type "dummyShip" as defined in the definition file.)

When I started attempting to write JUnit tests, I quickly realized what a world of hurt I've gotten myself into. A Ship depends on a ShipWeapon; to test a Ship, you need a ShipWeapon, ShipProvider, and even a WeaponProvider. To even test a ShipWeapon's fire method, you need two Ships: a source (the Ship doing the firing) and a target to shoot at. Research into this problem suggested that I have a tight coupling problem; what I could not find, however, is how I might loosely couple this particular set of classes. How might I go about doing this?

Rayhawk11
  • 41
  • 4
  • You don't create actual objects for unit tests, you create mocks which pretend to exhibit the behavior you're testing in a given test case. Check out Mockito. – daniu Apr 21 '18 at 19:09

1 Answers1

0

Talking about the firing, I would say it is a case for visitor pattern (https://en.wikipedia.org/wiki/Visitor_pattern), where Your ShipWeapon is the visitor and Ship is accepting entity.

Also for a more simple way of creating your Ships I would recommend using a Factory or Abstract Factory pattern (https://en.wikipedia.org/wiki/Abstract_factory_pattern).

Jakub Moravec
  • 181
  • 1
  • 10
  • I'm a little bit confused--How would a Visitor pattern help me here? ShipWeapon should only ever "visit" a Ship; I've no need for ShipWeapon to ever visit any other object. Isn't that the point of the Visitor pattern? (Note: I am quite inexperienced with this particular design pattern.) – Rayhawk11 Apr 21 '18 at 21:04