【发布时间】:2014-09-30 21:56:31
【问题描述】:
系统: Java 1.7 Grails 2.2
在我的域对象中:
class Timer{
BigDecimal hours
static constraints = {
hours min: 0.5, validator: { h ->
// The hours has to be a number in whole or half hour increments.
System.out.println "h:" + h.toString()
// Twice the number :
def h2 = 2 * h
// Extract h2 fractional portion:
String numberStr = Double.toString(h2);
String fractionalStr = numberStr.substring(numberStr.indexOf('.') + 1);
int fractional = Integer.valueOf(fractionalStr);
System.out.println "fraction:" + fractional
// if the fraction is 0 then "h" is a multiple of 0.5
// ie: h = 1.5 => h2 = 3.0, fractional = 0 return TRUE
// ie: h = 1.1 => h2 = 2.2, fractional = 2 return FALSE
(fractional == 0)
}
}
}
在单元测试中
@Build(Timer)
class TimerTests {
@Before
void setUp() {
// Ensure we can invoke validate() on our domain object.
mockForConstraintsTests(Timer)
}
/**
* Ensure setup creates a valid instance
*/
void testValid() {
Timer t = Timer.build()
assertTrue t.validate()
}
/**
* hours must be a number
*/
void testHours(){
Timer m = Timer.build()
assertTrue m.validate()
t.hours = 1;
assertTrue m.validate()
t.hours = 1.5;
assertTrue m.validate()
t.hours = 1.3;
assertFalse m.validate()
assertEquals 'validator', t.errors['hours']
// Test Min constraint
t.hours = 0;
assertFalse t.validate()
assertEquals 'min', t.errors['hours']
//
// Test non numbers
t = new Timer()
t.hours = "ss"
assertFalse t.validate()
}
}
我收到错误 org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'ss' with class 'java.lang.String' to class 'java.math.BigDecimal'
我想确保不能输入字符串,并且小时字段以整小时或半小时为增量。
欢迎提出任何建议。
谢谢
【问题讨论】:
-
您的测试表明它不能是字符串。您需要更改您的代码以期望出现异常。