The correct way to metaprograms in the grail so that it is available in unit tests

I can add a method to the java Integer type in Groovy with the lines:

ExpandoMetaClass.EnableGlobally() Integer.metaClass.gimmeAP = {->return 'p'} 

I donโ€™t know why I need it, but it makes sense. Now I can make calls to โ€œWholeโ€ and return โ€œpโ€. Now let me say that I want this in a grails application so that I can make calls on domain objects. The specific problem I am facing is that when I put these metaprogramming lines in bootstrap, all metaprogramming is not available in unit tests, so my unit tests fail with errors like "Without the gimmeAP method for java.lang.Integer", or something like that.

How should I turn on metaprogramming or run that part of the bootstrap so that I can use my cheated syntax in unit tests?

I saw this question: Grails is creating methods globally and metaclassing , and it seems that my ExpandoMetaClass.EnableGlobally() can fix its problem, but am I using it right?

+4
source share
1 answer

Bootstrap is not performed for unit tests. I personally would prefer to create a mockFoo method that does the above meta-programming, and then I will call mockFoo from the test setup. Also look at GrailsUnitTestCase.registerMetaClass. Register the metaclass before adding mock methods so that they donโ€™t leak in other tests.

  registerMetaClass(SecurityUtils) SecurityUtils.metaClass.'static'.getSubject = { -> return [logout: { return true } ] as Subject } 

I know that you want your dynamic methods to be available for all unit tests, but there is nothing like a bootstrap for unit tests. Therefore, you must do this in every test.

You can create a MockHelper with a static method and call it from test setUp.

+2
source

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


All Articles