Highlight one test device method in Groovy

I have a simple class like

class SomeClass { def foo() { def bar= bar() switch( bar ) { return something based on format } } def bar() { return someValue } } 

I have already written complete unit tests for bar() . Now I need to write unit tests for foo() , which is highly dependent on the use of the bar() method. I donโ€™t want to duplicate the installation phase the way it was done for bar() , so I would like to mock it by simply returning the desired values.

I know that Groovy easily supports this type of "ridicule" by simply defining it as SomeClass.property = "Hello World" . In addition, this can be done with employees like SomeClass.service = myMockedService . But I did not find a way to do this using the methods inside the device under test. There is?

I tried with MockFor , as in

 def uut = new MockFor( SomeClass ) uut.demand.bar{ /* some values */ } uut.use { assert uut.foo() == expected } 

but it gives me

 groovy.lang.MissingMethodException: No signature of method: groovy.mock.interceptor.MockFor.foo() is applicable for argument types: () values: [] 

UPDATE

In fact, I came up with a simple solution for using a subclass. In the testing method, I create a subclass of SomeClass , where I override the method that I want to mock / stub. After that, using an instance of the subclass gives me what I need.

It seems a little rude. Any other suggestions on this?

0
source share
1 answer

If you want to make fun of the value returned by bar() for a single instance of SomeClass , you can use metaprogramming. In the Groovy console, do the following:

 class SomeClass { def foo() { } def bar() { return 'real value' } } def uut = new SomeClass() uut.metaClass.bar = { return 'mock value' } assert 'mock value' == uut.bar() 

If you want to make fun of bar() for all instances of SomeClass , replace this:

 uut.metaClass.bar = { return 'mock value' } 

with:

 SomeClass.metaClass.bar = { return 'mock value' } 
+2
source

All Articles