I am trying to test my method which uses scanner object and dynamic input from keyboard by user. I could not figure out a way to test it. The thing is that the method which I want to use is also used in another method's loop. I think that Mockito can come in handy in this particular situation, unfortunately, I could not find out the way of how to test it. If that particular method is trying to return wrong value which would throw an exception. Well, code will provide deeper explanation (I hope).
/**
* This method asks user to insert cash
* It gets the property text from properties file by key insert.cash
* Checks if coin is in proper format
* Checks if coin exists in available coins array
* Otherwise throws exception
* @throws InvalidCoinException
* @return cash - how much money user inserted
*/
@Override
public double insertCash() throws InvalidCoinException {
double cash = 0;
double temp; // temporary variable which goes through all if statems if all conditions are satisfied it gets assigned to cash variable
boolean coinExists = false;
System.out.println(prop.getProperty("insert.cash"));
if(!sc.hasNextDouble()) {
throw new InvalidCoinException(MessageFormat.format(prop.getProperty("invalid.coin"), sc.next()));
}
else {
temp = sc.nextDouble();
for(int i = 0; i < availableCoins.length; i++) {
if(temp == availableCoins[i] || temp == 0) {
coinExists = true;
}
}
if(coinExists == true) {
cash = temp;
}
else {
throw new InvalidCoinException(MessageFormat.format(prop.getProperty("invalid.coin"), temp));
}
}
return cash;
}
JUNIT:
@org.junit.Before
public void initializeTest() throws IOException {
machine = new CoffeeMachineImplementation();
machineSpy = Mockito.spy(CoffeeMachineImplementation.class);
}
@org.junit.Test
public void testInsertCash() throws InvalidCoinException {
System.out.println("---------------- Insert cash -----------------");
Double input2 = 0.06;
Double input3 = 200.0;
Double input4 = 0.02;
try {
when(machineSpy.insertCash()).thenReturn(input2)
.thenThrow(new InvalidCoinException("..."));
fail("Should have thrown an exception " + input2);
}
catch (InvalidCoinException e) {
String exception = "Invalid coin: " + input2 + " euro is not existing coin";
System.out.println(e.getMessage());
assertEquals(exception, e.getMessage());
}
My scanner object is declared in constructor (because not only one method uses scanner):
public CoffeeMachineImplementation() throws IOException {
prop = new Properties();
input = new FileInputStream("src/localization.properties");
maWaterCap = 5;
maCoffeeCap = 3;
prop.load(input);
sc = new Scanner(System.in);
}