Controller and Service Grails Spock

Hi, I have a controller called ApiController that uses the ApiService service like this:

def createCategory(){ def jsonObj = request.JSON jsonObj.each{ key, value -> params.put(key,value) } render apiService.createCategory(params) } 

Which works great. But I can not write a test for this.

Here is how far I got:

 @TestFor(ApiController) @Mock([Category,ApiService]) class CategorySpec extends Specification { def setup() { } def cleanup() { } void "test"() { setup: def apiService = Mock(ApiService) when: request.method = 'POST' request.requestMethod = 'POST' params.categoryID = 'test' controller.createCategory() then: println(response) 1==1 } 

From this I get the following error:

 java.lang.NullPointerException: Cannot invoke method createCategory() on null object 

This is obviously because it cannot see my apiService bean. So my question is: how to do this in Spock?

+5
source share
3 answers

Most likely it will be with a Transactional bug : https://github.com/grails/grails-core/issues/1501

 ApiService apiService = new ApiService() controller.apiService = apiService apiService.transactionManager = Mock(PlatformTransactionManager) { getTransaction(_) >> Mock(TransactionStatus) } 

This is a temporary fix (as per the error report comment) ... it worked for me :)

+7
source

Here's how I would do it in Grails 2.4 without the @Mock annotation in the spec class:

 when: def serviceMock = mockFor(ApiService) serviceMock.demand.createCategory { def params -> "output sample" } controller.apiService = serviceMock.createMock() controller.createCategory() 
+1
source

ApiService mocks successfully in the test, but how do you give the layout to the controller? The device specifications lack DI, you cannot expect it to be auto-notified. Consequently,

 setup: controller.apiService = Mock(ApiService) 
0
source

Source: https://habr.com/ru/post/1206619/


All Articles