Grails UnitTest确保BigDecimal不是字符串

时间:2014-09-30 21:56:32

标签: java grails groovy

系统: 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:无法将类'java.lang.String'的对象''转换为类'java.math.BigDecimal'

我想确保无法输入字符串,并且小时字段以整数或半小时为增量。

欢迎任何建议。

由于

1 个答案:

答案 0 :(得分:2)

问题如下:

t.hours = "ss"

您正在为String类型的属性分配BigDecimal值。

如果您让数据绑定系统执行分配,那么您可以通过直接为属性分配值来利用一系列功能。

以下测试将通过(为简单起见,我将.build()内容从混合中删除了):

package demo

import grails.test.mixin.*
import org.junit.*

@TestFor(Timer)
class TimerTests {

    @Before
    void setUp() {
        // Ensure we can invoke validate() on our domain object.
        mockForConstraintsTests(Timer)
    }

    void testHours(){
        Timer m = new Timer(hours: 1)
        assertTrue m.validate()

        m.hours = 1.5;
        assertTrue m.validate()

        m.hours = 1.3;
        assertFalse m.validate()
        assertEquals 'validator', m.errors['hours']

        // Test Min constraint
        m.hours = 0;
        assertFalse m.validate()
        assertEquals 'min', m.errors['hours']

        // Test non numbers
        m = new Timer(hours: 'ss')
        assertFalse m.validate()
    }
}

我希望有所帮助。

相关问题