Reputation: 153
I have some unit test write in spock framework. But my test always is correct, even when I pass incorrect values.
class CalculatorTest extends Specification {
def "Method should return roman number"() {
given:
CalculatorApi romanCalculator = Mock()
when: "I add two numbers as integer"
romanCalculator.add(2, 2)
then: "Method should return roman number as String"
romanCalculator.add(2, 2) >> 32131
}
Method "add" should return String. In this test a say a method should return Integer.
public class RomanCalculator implements CalculatorApi {
private RomanConverter romanConverter;
public RomanCalculator() {
this.romanConverter = new RomanConverter();
}
public String add(int one, int two) throws OperationFail {
int number = one + two;
try {
return romanConverter.convertNumber(number);
} catch (NumberNotFound e) {
throw new OperationFail(e.getMessage());
}
}
public class RomanConverter implements ConverterApi {
public String convertNumber(Integer number) throws NumberNotFound {
switch(number) {
case 1:
return "I";
case 2:
return "II";
case 3:
return "III";
case 4:
return "IV";
case 5:
return "V";
case 6:
return "VI";
case 7:
return "VII";
case 8:
return "VIII";
case 9:
return "IX";
case 10:
return "X";
default:
throw new NumberNotFound();
}
}
Why this method not working? I just start learn unit testing with mock.
Upvotes: 0
Views: 70
Reputation: 1327
The question is: why you should mock? Mock is used to ensure that there are no other dependencies, in order to test a specific method. All the external dependencies can be mocked to avoid problems (E.G database connection: you want to test a logic which uses data retrieved from database, so you want to mock the object that is doing the database request). Also, please add details of what Mock library are you using.
Here you're saying that if you will call your method with parameter (2,2) it will return the execution of roman calculator (2,2), which is wrong. You're not testing here, Mock is not used to test the class you want to test, but to simplify the other object and test your methods in a safe and controlled environment. example:
Instance retrieve = new Instance()
method doSomething() {
retrievedVal = retrieve.retrieveFromDB(something)
return transform(retrievedVal)
}
your test should be:
test() {
Instance retrieve = mock()
when retrieve(specific something).thenReturn(specificRetrievedVal)
test doSomething()
}
I avoided a complete and fully example so you can understand how exactly you need to do and try :)
Upvotes: 2