Spock does not work for an expected "matched invocations" working through #WebAppConfiguration - spock

I am working with
STS
Gradle
Spock Core
Spock Reports
Spock Spring
Spring MVC Testing
I have the following test code:
#WebAppConfiguration
#ContextConfiguration(classes=[RootApplicationContextConfig.class,ServletApplicationContextConfig.class])
#SuppressWarnings("deprecation")
class PersonaXmlFindOneControllerTest extends Specification {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private PersonaXmlFindOneController personaXmlFindOneController
def setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
personaXmlFindOneController = webApplicationContext.getBean(PersonaXmlFindOneController.class);
println personaXmlFindOneController.toString()
}
def "findOneRequestParamById deberia ser llamado"(){
String url = null
ResultActions resultActions = null
given: "The URL being used "
url = "some url to test"
when: "When the URL is being calling with a GET"
resultActions = mockMvc.perform(get(url, PersonaControllerSupport.ID)).andDo(print())
then: "...."
resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("persona").exists())
.andExpect(xpath("persona").nodeCount(1))
….
//then:
//1 * personaXmlFindOneController.findOneRequestParamById(_ as String)
}
The code works fine. It pass.
Furthemore: through Gradle Test Report thanks to andDo(print()) I can confirm that personaXmlFindOneController.findOneRequestParamById has been called.
It means
Handler:
Type = com.manuel.jordan.controller.xml.PersonaXmlFindOneController
Method = public com.manuel.jordan.domain.xml.PersonaXml com.manuel.jordan.controller.xml.PersonaXmlFindOneController.findOneRequestParamById(java.lang.String)
Now If enable
//then:
//1 * personaXmlFindOneController.findOneRequestParamById(_ as String)
The code fails,
Too few invocations for:
1 * personaXmlFindOneController.findOneRequestParamById(_ as String) (0 invocations)
Unmatched invocations (ordered by similarity):
None
Observe that in the setup method, it has been retrieved through
personaXmlFindOneController = webApplicationContext.getBean(PersonaXmlFindOneController.class);
Therefore, what is missing or what is wrong?

You are mixing two different mocking mechanisms.
There is the Spring one (MockMVC) and the Spock one.
Spock can only verify mocks created by itself (.i.e those created with the Spock Mock() method). You don't create any Spock mocks in your code and therefore Spock mocking will not work.
See the official documentation of Spock for the full mocking guide to understand how you can create mocks with Spock only.
In your particular example your original code is correct and it should stay that way. You don't always have to use the Spock mocking mechanism. Having a Spock test that uses only Spring testing facilities is perfectly fine.

Related

Grails, Integration Testing, mocking a bean method while testing a service with Spock

I'm having an issue performing an integration test in Grails 2.4.5.
The service I want to test looks like this:
class MyService {
def myBean
def serviceMethod() {
myBean.beanMethod()
}
}
where myBean is defined in resources.groovy:
beans = {
myBean(MyBeanImpl)
}
And here comes the integration test:
MyServiceIntegrationSpec extends IntegrationSpec {
def myService
def setup() {
def myBeanMock = Mock(MyBeanImpl)
myBeanMock.beanMethod(_) >> 'foo'
myService.myBean = myBeanMock
}
void "silly test"() {
expect:
myService.serviceMethod() == 'foo'
}
}
Well, this badly fails since myService.serviceMethod() returns null.
I've already tried
ReflectionTestUtils.setField(myService, 'myBean', myBeanMock)
instead of
myService.myBean = myBeanMock
with no luck.
Of course this simplified example could be handled with a unit test, but the real case I'm facing needs an integration test since data persistence is involved.
myBeanMock.beanMethod(_) >> 'foo' expects one parameter.
You can either use
myBeanMock.beanMethod() >> 'foo'
or
myBeanMock.beanMethod(*_) >> 'foo'.
Either case mocking should not be part of Integration spec because this is an integration test. In your case as explained, there might be a need.

What is wrong with my Spec?

So, I have this pretty simple Spec below. I have a class that is not a controller or service or anything like that. It's a Job class. It depends on two services: updateService and directoryTypeService. It runs a Redis async job and it's under /grails-app/jobs folder.
All I want is to make sure that whenever I invoke this job#perform() method (which return type is void), a given dependent method called UpdateService#completeClaiming is invoked, but UpdateService#requestNewPin is not. (Listing is a domain class, by the way).
When I run this Spec, I keep getting an error message saying: "No more calls to 'completeClaiming' expected at this point. End of demands."
What am I doing wrong here? Any wild guesses?
#Mock(Listing)
class SubmissionJobSpec extends Specification {
def directoryTypeServiceMock
def updateServiceMock
def job
def setup(){
job = new SubmissionJob()
directoryTypeServiceMock = mockFor(DirectoryTypeService)
updateServiceMock = mockFor(UpdateService)
job.updateService = updateServiceMock.createMock()
job.directoryTypeService = directoryTypeServiceMock.createMock()
}
def "if the directory is enabled and the pin status is ENTERED, we should call updateService.completeClaiming"() {
given:
directoryTypeServiceMock.demand.isUpdateEnabled { DirectoryType d, Country c -> return true}
new Listing(
location: new Location(country: Country.DE)
).save(failOnError: true, validate: false)
when:
job.perform(Listing.last().id, true)
then:
1 * updateServiceMock.completeClaiming(Listing.last(), true) >> new ListingEvent(output: [success: true])
0 * updateServiceMock.requestNewPin(_ as Listing, true)
}
You seem to be confusing Groovy and Spock mocks. You can't use Spock mocking syntax (e.g. 0 * updateServiceMock.requestNewPin(_ as Listing, true)) for a Groovy mock created with mockFor(). Spock mocks are created using Mock(), Stub() or Spy(). I'm not aware of any good reason to use a Groovy mock in a Spock spec.

integration testing in Grails: what is the correct way?

I'm entirely new to Grails and it's testing functions since I started my current job approx 4 months ago. The person who trained me on testing left our group several weeks ago, and now I'm on my own for testing. What I've slowing been discovering is that the way I was trained on how to do Grails integration testing is almost entirely different from the way(s) that I've seen people do it on the forums and support groups. I could really use some guidance on which way is right/best. I'm currently working in Grails 2.4.0, btw.
Here is a sample mockup of an integration test in the style that I was trained on. Is this the right or even the best way that I should be doing it?
#Test
void "test a method in a controller"() {
def fc = new FooController() // 1. Create controller
fc.springSecurityService = [principal: [username: 'somebody']] // 2. Setup Inputs
fc.params.id = '1122'
fc.create() // 3. Call the method being tested
assertEquals "User Not Found", fc.flash.errorMessage // 4. Make assertions on what was supposed to happen
assertEquals "/", fc.response.redirectUrl
}
Since Grails 2.4.0 is used, you can leverage the benefit of using spock framework by default.
Here is sample unit test case which you can model after to write Integration specs.
Note:
Integration specs goes to test/integration
should inherit IntegrationSpec.
Mocking is not needed. #TestFor is not used as compared to unit spec.
DI can be used to full extent. def myService at class level will inject the service in
spec.
Mocking not required for domain entities.
Above spec should look like:
import grails.test.spock.IntegrationSpec
class FooControllerSpec extends IntegrationSpec {
void "test a method in a controller"() {
given: 'Foo Controller'
def fc = new FooController()
and: 'with authorized user'
fc.springSecurityService = [principal: [username: 'somebody']]
and: 'with request parameter set'
fc.params.id = '1122'
when: 'create is called'
fc.create()
then: 'check redirect url and error message'
fc.flash.errorMessage == "User Not Found"
fc.response.redirectUrl == "/"
}
}

Grails spock database locking

I have a service method that locks a database row.
public String getNextPath() {
PathSeed.withTransaction { txn ->
def seed = PathSeed.lock(1)
def seedValue = seed.seed
seed.seed++
seed.save()
}
}
This is how my spock test looks like:
void "getNextPath should return a String"() {
when:
def path = pathGeneratorService.getNextPath()
then:
path instanceof String
}
It's just a simple initial test. However I get this error when I run the test:
java.lang.UnsupportedOperationException: Datastore [org.grails.datastore.mapping.simple.SimpleMapSession] does not support locking.
at org.grails.datastore.mapping.core.AbstractSession.lock(AbstractSession.java:603)
at org.grails.datastore.gorm.GormStaticApi.lock_closure14(GormStaticApi.groovy:343)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:302)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:37)
at org.grails.datastore.gorm.GormStaticApi.lock(GormStaticApi.groovy:342)
at com.synacy.PathGeneratorService.getNextPath_closure1(PathGeneratorService.groovy:10)
at org.grails.datastore.gorm.GormStaticApi.withTransaction(GormStaticApi.groovy:712)
at com.synacy.PathGeneratorService$$EOapl2Cm.getNextPath(PathGeneratorService.groovy:9)
at com.synacy.PathGeneratorServiceSpec.getNextPath should return a String(PathGeneratorServiceSpec.groovy:17)
Does anyone have any idea what this is?
The simple GORM implementation for Unit tests does not support some features, such as locking. Moving your test to an integration test will use the full implementation of GORM instead of the simple implementation used by unit tests.
Typically when you find yourself using anything more than the very basic features of GORM you will need to use integration tests.
Updated 10/06/2014
In more recent versions of Grails and GORM there is now the HibernateTestMixin which allows you to test/use such features in Unit tests. Further information can be found in the documentation.
As a workaround, I was able to get it working by using Groovy metaprogramming. Applied to your example:
def setup() {
// Current spec does not test the locking feature,
// so for this test have lock call the get method
// instead.
PathSeed.metaClass.static.lock = PathSeed.&get
}

Integration Tests started to fail with grails upgrade

I upgraded a grails app from 1.2.2 to 1.3.7 after this upgrade a few integration tests have started to throw the following error the 'validateAndSaveList' is a method on a service used by the service I'm testing. These tests were passing before the upgrade and they will also pass if I run just the integration test phase with grails test-app -integration
junit.framework.AssertionFailedError:
No more calls to 'validateAndSaveList'
expected at this point. End of
demands.
Code:
import com.e.domain.*
import com.e.exception.GORMServiceException
import com.e.controller.SecurityUserCommand
class AccountServiceTests extends GroovyTestCase
{
def accountService
void testRegisterWithMinimumInfo()
{
def clinic = new Clinic(name:'clinicName')
def securityUserCommand = new SecurityUserCommand(username:'username', password:"password", confirm:"password")
def clinicUser = new ClinicUser(firstName:'fname', lastName:'lname', emailAddress:'abc#abc.com')
clinicUser.clinic = clinic
//clinicUser.securityUser = securityUser
clinic.address = new Address()
// TODO - JsecUser no longer in use
def role = new ShiroRole(name:'TEST')
//def subscription = ESubscription.findByName('Charter Member')
def subscription = new ESubscription(
name:'Charter Member',
description:'Charter Member',
periodType:'Monthly',
numPeriods:12,
amountPerPeriod:25.00,
electronicSubmissionRate:0.00,
accountingRate:0.01,
numAllowedUsers:4,
startDate: today -1,
endDate: today+1
)
subscription.save(flush:true)
if(subscription.hasErrors())
println subscription.errors
assertNotNull subscription
clinicUser.empathicCustomerProfile.subscription = subscription
def result = accountService.register(clinic, securityUserCommand, clinicUser, role)
assert result.success
assert result.clinic.id
assert result.securityUser?.id
assert result.clinicUser.id
}
StackTrace
junit.framework.AssertionFailedError: No more calls to 'validateAndSaveList' expected at this point. End of demands.
at grails.test.MockClosureProxy.doBeforeCall(MockClosureProxy.java:66)
at grails.test.AbstractClosureProxy.call(AbstractClosureProxy.java:74)
at grails.test.GrailsMock$_createMock_closure1.doCall(GrailsMock.groovy:125)
at com.e.service.AccountService.register(AccountService.groovy:46)
at com.e.service.AccountService$register.call(Unknown Source)
at AccountServiceTests.testRegisterWithMinimumInfo(AccountServiceTests.groovy:53)
this answer comes from working the issue out in the comments:
the exception you are getting clearly indicates that somewhere you have put a mock object in your service, and the service is calling the mock object in a way it was not set up to handle.
The root problem as seen from #hvgotcodes is that there was a mock object for the service even though in that given test there was no mocking happening.
This happened in grails 1.3.7
I found a unit test that was doing the following:
def dataBindServiceControl = mockFor(DataBindService)
dataBindServiceControl.demand.safeBind{}
dataBindServiceControl.demand.extractPhones{}
dataBindServiceControl.demand.validateAndSaveList{l-> return true}
def dataBindService = dataBindServiceControl.createMock()
controller.dataBindService = dataBindService
If those tests were removed then all the integration tests would pass so to solve with out rewriting the tests I added the following to the tear down method.
GroovySystem.metaClassRegistry.removeMetaClass(DataBindService)
With this addition the tests are now working correctly in grails 1.3.7

Resources