import com.demo.SimpleController
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import spock.lang.Specification
@TestFor(UrlMappings)
@Mock(SimpleController)
class UrlMappingsSpec extends Specification {
// ...
}
15.1.5 Unit Testing URL Mappings
Version: 3.2.7
15.1.5 Unit Testing URL Mappings
The Basics
Testing URL mappings can be done with the TestFor annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following:
As you can see, any controller that is the target of a URL mapping that you’re testing must be added to the @Mock annotation.
Note that since the default UrlMappings class is in the default package your test must also be in the default package
|
With that done there are a number of useful methods that are defined by the grails.test.mixin.web.UrlMappingsUnitTestMixin for testing URL mappings. These include:
-
assertForwardUrlMapping- Asserts a URL mapping is forwarded for the given controller class (note that controller will need to be defined as a mock collaborate for this to work) -
assertReverseUrlMapping- Asserts that the given URL is produced when reverse mapping a link to a given controller and action -
assertUrlMapping- Asserts a URL mapping is valid for the given URL. This combines theassertForwardUrlMappingandassertReverseUrlMappingassertions
Asserting Forward URL Mappings
You use assertForwardUrlMapping to assert that a given URL maps to a given controller. For example, consider the following URL mappings:
static mappings = {
"/actionOne"(controller: "simple", action: "action1")
"/actionTwo"(controller: "simple", action: "action2")
}
The following test can be written to assert these URL mappings:
import com.demo.SimpleController
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import spock.lang.Specification
@TestFor(UrlMappings)
@Mock(SimpleController)
class UrlMappingsSpec extends Specification {
void "test forward mappings"() {
expect:
assertForwardUrlMapping("/actionOne", controller: 'simple', action: "action1")
assertForwardUrlMapping("/actionTwo", controller: 'simple', action: "action2")
}
}
Assert Reverse URL Mappings
You use assertReverseUrlMapping to check that correct links are produced for your URL mapping when using the link tag in GSP views. An example test is largely identical to the previous listing except you use assertReverseUrlMapping instead of assertForwardUrlMapping. Note that you can combine these 2 assertions with assertUrlMapping.