15.1.5 Unit Testing URL Mappings - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.9
15.1.5 Unit Testing URL Mappings
The Basics
Testing URL mappings can be done with theTestFor annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following: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 { // … }
@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 actionassertUrlMapping- Asserts a URL mapping is valid for the given URL. This combines theassertForwardUrlMappingandassertReverseUrlMappingassertions
Asserting Forward URL Mappings
You useassertForwardUrlMapping 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") }
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 useassertReverseUrlMapping 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.
