2

I'm building an automatic game client that is supposed to make moves against me in a 4-Wins-Game. For making a move it should chose a column and send that chosen column by calling the move() function to my server.

public class AutomaticGameClient {

  private String userName;      
  private String userPassword;

  public AutomaticGameClient(String userName, String userPassword) {
    this.userName = userName;
    this.userPassword = userPassword;
  }

  public int makeMove() {
      columnNo = 0;
      move(columnNo);
      return columnNo;
  }

}

Right now it always simply moves by making the next move in the first row (columnNo = 0). This works. Now I have to test that function, but I don't want to test the move() part. I only want to assert, that it's returning 0:

  @Test
public void whenMakeMove_columnNoIsZero() {
    AutomaticGameClient agcY = new AutomaticGameClient("Georg1", "geheim1");
    int rowMoved = agcY.makeMove();
    assertEquals(rowMoved, 0);

}

When I run this test, I get org.java_websocket.exceptions.WebsocketNotConnectedException, because move(columnNo) is trying to start a connection to my socket. So is there a way to skip this part of the function under test?

Turing85
  • 18,217
  • 7
  • 33
  • 58
luda-chris
  • 33
  • 4

1 Answers1

2

"So is there a way to skip this part of the function under test?" - Yes. One could create a partial mock/spy of the unit under test and then mock the move(...)-method. For more details please refer to this posts by Victor Grazi and its answers.

In this concrete situation, however, the cleaner solution would be to move socket-related code to a separate service. A unit should be tested as a unit and thus we should use mocks seldomly and only if no other possibility exists. This, however, is a boundary between units, thus socket-communication should be moved in a separate unit for better testability. Please notice that I do not say that each class is a unit. A unit can be composed of multiple classes. But one class should not be composed of multiple units since we then have to resort to solutions like partial mocks for the unit under test. In my opinion, mocking the unit under test is always a red flag.

Turing85
  • 18,217
  • 7
  • 33
  • 58