Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a complicated method

I'm working on a checkers implementation where I have dozens of easily tested methods, but I'm not sure how to test my main #play_game method. Where most of my methods have easily determined inputs and outputs, and are, therefore, easy to test, this method is multifaceted and really doesn't have an easily discernible output. Here is the code:

def play_game
    puts @gui.intro

    while(game_over? == false)
      message = nil
      @gui.render_board(@board)
      @gui.move_request
      player_input = gets 
      coordinates = UserInput.translate_move_request_to_coordinates(player_input) 

      message = MoveCheck.move_validator(coordinates[0], coordinates[1], coordinates[2], coordinates[3])
      puts message unless (message.nil? or message == "jumping move")
      if(message == nil or message == "jumping move")
        @current_player = switch_player unless (message == "jumping move" and jump_available? == true)
      end
    end
    puts @gui.display_game_ending_message  
  end

So how can I test this (using RSpec) or should I not worry about it and really on my otherwise comprehensive testing?

like image 488
steve_gallagher Avatar asked Nov 30 '11 17:11

steve_gallagher


People also ask

How complex should unit tests be?

The general rule for unit tests is to test the smallest possible piece that you can test. A good rule is that each test should exercise exactly a single method from a public API. That means it should only execute this method and no other, not even transiently.

What makes a good unit test?

Good unit tests should be reproducible and independent from external factors such as the environment or running order. Fast. Developers write unit tests so they can repeatedly run them and check that no bugs have been introduced.

What should be tested in unit testing?

A unit test is a way of testing a unit - the smallest piece of code that can be logically isolated in a system. In most programming languages, that is a function, a subroutine, a method or property. The isolated part of the definition is important.


1 Answers

All play_game is really doing is running the game loop. What you are really looking to test is what happens inside the game loop. The easiest way to do that is to break the content of the game loop down into more easily testable methods.

Once you have the game loop as just a series of methods, you can then much more easily test each of them in isolation.

like image 183
cdeszaq Avatar answered Oct 04 '22 23:10

cdeszaq