我有一些單元測試寫在spock框架中。但是我的測試總是正確的,即使我傳遞了錯誤的值。爲什麼模擬方法總是正確的?
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
}
方法「add」應該返回String。在這個測試中,一個方法應該返回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();
}
}
爲什麼這種方法不工作?我剛開始學習模擬單元測試。
這是什麼碼手段? 'romanCalculator.add(2,2)>> 32131' – roeygol
嘲笑你正在測試的類是毫無意義的。 –
這意味着參數爲2和2的方法應返回值32131 – dejmien25