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?
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'
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()
While the controller method save does not get null object anymore, the properties that the JSON data are supposed to set are not set.
After starting a different project and doing mostly the same thing, everything worked even binding properties to method argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With