Reputation: 2849
I am trying to write unit tests for a game i have created. The game is a tic tac toe implementation which interacts with the user and takes input from the command line. I am not sure how i can go about writing a test which will take and check user input. For example: When run: the program asks user for entering name and his symbol ('x' or '0') and then keep accepting inputs of position.
Do i create a @Before method and write input statements inside this method? or is there a better way to do this? Writing everything in my @Before method will make it extremely big.
Any suggestions?? Please help.
Thank you
Upvotes: 1
Views: 2706
Reputation: 15868
Ideally, you'd split your input class into an interface and an implementation, and then create a MockInput for testing purposes.
interface IUserInput {
public String getUserName();
public XO_Enum getUserSymbol();
}
class MockUserInput implements IUserInput {
private XO_Enum xo;
private String name;
public MockUserInput(String name_, XO_Enum xo_) {
xo = xo_;
name = name_;
}
public String getUserName() { return name; }
public XO_Enum getUserSymbol() { return xo; }
}
When some test needed a fake user input, you just whip up a mock one for the occasion and keep going. The symbol and name could be hard-coded, but this way gives you some flexibility.
Given hhafez's answer, one of us is clearly answering the wrong question... and I'm not so sure it's him. Ah well, this'll be helpful either way.
Upvotes: 1
Reputation: 39750
You say you want to write
a test which will take and check user input
You shouldn't have one class that does both, take and check user input, that's poor cohesion. Instead have two classes a Validator (or checker or what ever you want to call it) and an input processor that takes the user input and builds some object that the Validator understands.
Once you have separated the concerns, writing a junit test case for your Validator should be quite straightforward. As for the user input class have a look at this question about how to unit test console based app
Upvotes: 1