Reputation: 141
double checkAndReturnDoubleIfOk(String stringToCheck) {
double price = 0;
try {
price = Double.valueOf(stringToCheck);
} catch (NumberFormatException e) {
System.err.println("Price is not a number");
return -1;
}
String[] array = stringToCheck.split("\\.");
if (array[1].length() < 3 & price > 0) {
return price;
} else {
throw new WrongCostFormat();
}
}
@Test(expected = WrongCostFormat.class)
public void shouldThrowNumberFormatException() {
Product mock = mock(Product.class);
double number = mock.checkAndReturnDoubleIfOk("1.234");
}
I'm new to JUnit and Mockito world and can't figure out, why the test is failed. Any suggestions? I've debugged the test file and it seems number is 0.0 rather than throwing an exception... package exceptions;
public class WrongCostFormat extends RuntimeException {
public WrongCostFormat() {
super();
}
public WrongCostFormat(String s) {
super(s);
}
public WrongCostFormat(String s, Throwable throwable) {
super(s, throwable);
}
public WrongCostFormat(Throwable throwable) {
super(throwable);
}
}
Upvotes: 2
Views: 1858
Reputation: 12953
When you mock an object, you don't really call the method of the mocked object, so the exceptions from inside your code will not be thrown.
The purpose of mocking is when you want to test one part of your code, and 'mock' some other parts of it to behave the way you need them to for the sake of the test- you should not mock the object you want to test, but the surronding objects.
There is no real need for mocking here, if you wan't to test checkAndReturnDoubleIfOk
, just run it from a real object, not a mocked one
Upvotes: 4
Reputation: 3415
If you want to test checkAndReturnDoubleIfOk
you should not mock it.
What you are doing is wrong -- you are meant to mock out collaborators, not the class under test. First you create a mock of Product
which has all methods mocked (checkAndReturnDoubleIfOk
also) and then try to use it as a original class. Actually your are testing mocked implementation of checkAndReturnDoubleIfOk
.
Your code should be something like this:
@Test(expected = WrongCostFormat.class)
public void shouldThrowNumberFormatException() {
Product p = new Product();
p.checkAndReturnDoubleIfOk("1.234");
}
When the class being tested uses another class, it's this other class that should be mocked. Then you should verify that the class being tested has interacted correctly with the mocked class.
Upvotes: 8