0

I have a weird problem with integration testing restful controllers... In the following code snippet, when I make a post request from tests, the save method of the parent, RestfulController class is called instead of the save method of the child class, MyController and because they have different signatures, this ends up resulting in a UNPROCESSIBLE_ENTITY response.

class MyController extends RestfulController<MyDomain> {
    static responseFormats = ['json', 'xml', 'hal']

    MyController() {
        super(MyDomain)
    }


    def save(MyCommand command) {
        ...
    }
}

When I run the following test, the save() action of my controller's parent class, RestfulController gets executed, thus leading to UNPROCESSIBLE_ENTITY response, since I am using a Command object which is different from my domain class.

void "Test the save action correctly persists an instance"() {
        when: "The save action is executed with valid data"

        response = restBuilder.post(resourcePath) {
            accept('application/json')
            header('Authorization', "Bearer ${accessToken}")
            json validJson
        }

        then: "The response is correct"

        response.status == CREATED.value()
        response.json.id
        Vote.count() == 1
    }

What can I do to fix this, please?

Pila
  • 5,460
  • 1
  • 19
  • 30

1 Answers1

0

Overloading controller actions is not supported. You can override them, but you can't overload them.

What is happening is the framework is invoking the no-arg save() action in the parent class, which never invokes your method (nor should it).

You can rename your save(MyCommand command) so it doesn't have the same name as an action in your parent class and then provide a corresponding URL mapping and you will be on your way. Depending on what you want to do in the action, that may or may not be the best thing, but that is 1 path you can take.

I hope that makes sense.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • Hi, @jeff-scott-brown the aspect of renaming the action makes complete sense. However, when I define the new action and a corresponding url for it, making the call returns a 404, even though running `grails url-mapping-report` clearly shows the url defined. What could be the issue? – Pila Apr 23 '18 at 09:39
  • Here is the url I defined; `"/api/votes"(controller: "vote", action: 'saveVote', method: 'POST')` changed from ``"/api/votes"(resources: "vote")` and now I am getting a `404` when I make post requests to the newly defined url. – Pila Apr 23 '18 at 09:47
  • @Pila Now you are dealing with a wholly different question. It is difficult to say why you are getting a 404 without seeing the code. – Jeff Scott Brown Apr 23 '18 at 11:18