Psycho Punch
Psycho Punch

Reputation: 6892

Grails - unit testing with using JSON request does not work

I have the following controller code:

@Transactional
def save(MyModel model) {
    model.save()
}

I'm testing it using:

request.json = new MyModel(property1: 1, property2: 2)
controller.save()

However, every time I run the test, I get NullPointerException, because model is null. Do I need to put any other code to get the binding to work properly?

Upvotes: 2

Views: 2407

Answers (2)

Psycho Punch
Psycho Punch

Reputation: 6892

In order to get the test code working, I called controller.request.json instead of just request.json. In addition, based on dmahapatro's answer, I set the the method to POST.

Here's how the working code looks like:

controller.request.method = 'POST'
controller.request.json = new MyModel(property1: 1, property2: 2)
controller.save()

Update

While the controller method save does not get null object anymore, the properties that the JSON data are supposed to set are not set.

Update 2

After starting a different project and doing mostly the same thing, everything worked even binding properties to method argument.

Upvotes: 4

dmahapatro
dmahapatro

Reputation: 50245

Setting domain object to request.json should work if the domain object is mocked appropriately in controller unit spec/test.

Instead, you can also set a JSON string to request.json in the test, which will then be bound to MyModel when controller action in called. So your test should look like:

request.json = '{"property1": 1, "property2": 2}'

Also note, since you do not have an id in the request payload, which indicates you are trying to POST a new record. In this case, the data binding with the domain object will only work if the http method is set to POST in the request explicitly.

request.method = 'POST'

Upvotes: 7

Related Questions