unit testing - How to JUnit test for any output in Java -
i'd test 2 methods below, because based on random output go-to assertequals()
won't work.
i want test ensure methods producing kind of output. ideas?
novice programmer, appreciate help.
public void comprandomchoice() { double choice = (math.random() * 100 / 100); if (choice > 0 && choice <= 0.34) { computer.setchoice(handthrow.rock); } else if (choice > 0.34 && choice <= 0.67) { computer.setchoice(handthrow.paper); } else { computer.setchoice(handthrow.scissors); } } public string gamewinner() { string gameresult; if (human.getchoice() == computer.getchoice()) { gameresult = "its tie!"; } else if (human.getchoice() == handthrow.rock && computer.getchoice() == handthrow.scissors || human.getchoice() == handthrow.paper && computer.getchoice() == handthrow.rock || human.getchoice() == handthrow.scissors && computer.getchoice() == handthrow.paper) { gameresult = "congrats, win!"; } else { gameresult = "computer wins!"; } return gameresult; }
i suggest changing comprandomchoice()
function follows
public void comprandomchoice(double rand_no) { double choice = (rand_no * 100 / 100); if (choice > 0 && choice <= 0.34) { computer.setchoice(handthrow.rock); } else if (choice > 0.34 && choice <= 0.67) { computer.setchoice(handthrow.paper); } else { computer.setchoice(handthrow.scissors); } }
then in program, can call comprandomchoice(math.random())
in unit tests, can hard-code input, e.g. comprandomchoice(0.5)
, assert result expected.
similarly, change public string gamewinner()
public string gamewinner(string human_choice, string computer_choice)
public string gamewinner(string human_choice, string computer_choice) { string gameresult; if (human_choice == computer_choice) { gameresult = "its tie!"; .......
in code, can call function gamewinner(human.getchoice(), computer.getchoice())
. in unit tests, can hard code input (using approach similar used previous function) , assert expected result based on parameter passing.
Comments
Post a Comment