Grails 2.1 Unit Testing Command Object mockForConstraintsTests not working?

烈酒焚心 提交于 2019-12-01 21:17:06

I believe I found the grails supported way to unit test Command objects in grails 2.0. You need to use mockCommandObject provided by the ControllerUnitTestMixin.

Credit to Erik

http://www.jworks.nl/2012/04/12/testing-command-objects-in-grails-2-0/

EDIT

Using validate() appropriately and mockForConstraintsTest should work if the patch mentioned in the existing Grails bug is in place (Thanks to @codelark for bringing that up). In order to test the command object from a Web App standpoint (using controller) the below information would be helpful.

Test Command Object Using Controller action:-

A command object is only deemed as such when it is used as a parameter in one of the action method inside a controller. Refer Command Objects (Warning NOTE). Use SearchCommand in an action method, you should be able to assertEquals.

Sample:

void testSomething() {
        YourController controller = mockController(YourController) //Or instantiate
        SearchCommand commandUnderTest = new SearchCommand ()
        //Note the usage here. validate() does not take parameters
        commandUnderTest.basisBuild = ''
        commandUnderTest.validate()

        //Call your action
        controller.searchCommandAction(commandUnderTest)

        assert response.text == 'Returned'
        assertEquals "blank", commandUnderTest.errors['basisBuild']
    }

YourController's action:-

def searchCommandAction(SearchCommand sc){
    render "Returned"
}

Note:

With out the patch from the grails bug we see the below error in @Grails 2.1.4, 2.2.0 & 2.2.1

I get an error when I only correct the validation and use mockForConstraintTests without using controller action:

You are using the validate method incorrectly. You never set the field on the class, so the field is null, not blank. Try changing your test as follows:

void testSomething() {
    SearchCommand commandUnderTest = new SearchCommand()
    commandUnderTest.basisBuild = ""

    assertFalse commandUnderTest.validate()
    assertEquals 'blank', commandUnderTest.errors['basisBuild']
}

Edit: There is also a grails bug when testing command classes that use the @Validatable annotation. There are some workarounds in the bug commentary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!