title: How do I configure mime types in a grails Spock test?
body: <p>Grails 2.3.10.</p>
  
  <p>How can I configure the available mime types for content type negotiation in a Grails Spock test?</p>
  
  <p>When I try to tell the controller to produce JSON content, it seems to want to return an HTTP 406 error. I send in the Accept header in my test code; but, the parser is not able to match it because HTML is the only MIME type that's configured.</p>
  
  <p><strong>My use case...</strong></p>
  
  <p>I have implemented a controller action using the Grails <em>respond</em> method which can return a JSON response. When I hit the endpoint using a REST API call, I am able to get back JSON output (even if no Accept header is specified).</p>
  
  <p>The controller code:</p>
  
  <pre><code>@Transactional(readOnly = true)
  class MyObjectController {
      static allowedMethods = [save: 'POST']
      static responseFormats = ['json']
      def myService
  
      @Transactional
      def save(MyObject obj) {
          obj.validate()
          if (obj.hasErrors()) {
              respond obj.getErrors(), [status: BAD_REQUEST]
          }
  
          myService.addNewCustomer(obj)
  
          respond obj, [formats: responseFormats]
      }
  }
  </code></pre>
  
  <p>And my test code:</p>
  
  <pre><code>@TestFor(MyObjectController)
  class MyObjectControllerSpec extends Specification {
      def setup() {
      }
  
      def cleanup() {
      }
  
      void "test save - json success"() {
          given:
          def myObj = new MyObject()
          controller.myService= Mock(MyObjectService)
  
          when:
          request.addHeader "Accept", "application/json"
          controller.save(individual)
  
          then:
          response.status == HttpStatus.CREATED.value()
          response.text == "{}"   //.text is giving me an empty string
          response.json.x == x    //.json throws an exception (parsing an empty string)
      }
  }
  </code></pre>
  
  <p>I have verified in the debugger that <em>obj</em> has a valid value and that the <em>respond</em> method is invoked on the last line of the controller action.</p>
  
  <p>What I am finding is that inside the Grails <strong>ResponseMimeTypesApi</strong> class, the <strong>DefaultAcceptHeaderParser</strong> is getting constructed with only the HTML mime type. Even though the JSON accept header is being read correctly, the <strong>DefaultAcceptHeaderParser</strong> isn't able to understand it because no mime types are configured.</p>
  
  <p>How do I control the mime types that get sent to <strong>ResponseMimeTypesApi</strong> in my unit test spec?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I have also tried setting the <em>response.format</em> property, as suggested in <a href="https://stackoverflow.com/a/16195621/166850">this answer</a>; but, to no avail.</p>