简体   繁体   中英

how to assert values inside “render” in unit test case (grails ,junit)

I was trying to assert the values inside "render" in my unit test cases written in Grails. But it does not seems to be proper

   render(view:"create",model[:])

what i tried was assertEquals("create",renderArgs("view"))

i also tried some alternatives like controller.response.renderedUrl etc. But none of those are working. Could someone give an idea?

Thanks in advance, BK

To test the view you can simply use an implicit view variable, though it will point to the path of your view/template, eg /controller/create . So you could write assertEquals(view, '/controller/create') . There is also an implicit model variable for which you can proceed similarly.

See docs ( Testing View Rendering section).

The following tests work:

grails-app/controllers/demo/DemoController.groovy:

package demo

class DemoController {

    def index() {
        render view: 'first'
    }
}

test/unit/demo/DemoControllerSpec.groovy:

package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoController)
class DemoControllerSpec extends Specification {

    void "test render view"() {
        when:
        controller.index()

        then:
        '/demo/first' == view
    }
}

test/unit/demo/DemoControllerTests.groovy:

package demo

import grails.test.mixin.TestFor

@TestFor(DemoController)
class DemoControllerTests {

    void testRenderView() {
        controller.index()
        assert '/demo/first' == view
    }
}

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM