How to test a Grails Service that utilizes a criteria query (with spock)? - unit-testing

I am trying to test a simple service method. That method mainly just returns the results of a criteria query for which I want to test if it returns the one result or not (depending on what is queried for).
The problem is, that I am unaware of how to right the corresponding test correctly. I am trying to accomplish it via spock, but doing the same with any other way of testing also fails.
Can one tell me how to amend the test in order to make it work for the task at hand?
(BTW I'd like to keep it a unit test, if possible.)
The EventService Method
public HashSet<Event> listEventsForDate(Date date, int offset, int max) {
date.clearTime()
def c = Event.createCriteria()
def results = c {
and {
le("startDate", date+1) // starts tonight at midnight or prior?
ge("endDate", date) // ends today or later?
}
maxResults(max)
order("startDate", "desc")
}
return results
}
The Spock Specification
package myapp
import grails.plugin.spock.*
import spock.lang.*
class EventServiceSpec extends Specification {
def event
def eventService = new EventService()
def setup() {
event = new Event()
event.publisher = Mock(User)
event.title = 'et'
event.urlTitle = 'ut'
event.details = 'details'
event.location = 'location'
event.startDate = new Date(2010,11,20, 9, 0)
event.endDate = new Date(2011, 3, 7,18, 0)
}
def "list the Events of a specific date"() {
given: "An event ranging over multiple days"
when: "I look up a date for its respective events"
def results = eventService.listEventsForDate(searchDate, 0, 100)
then: "The event is found or not - depending on the requested date"
numberOfResults == results.size()
where:
searchDate | numberOfResults
new Date(2010,10,19) | 0 // one day before startDate
new Date(2010,10,20) | 1 // at startDate
new Date(2010,10,21) | 1 // one day after startDate
new Date(2011, 1, 1) | 1 // someday during the event range
new Date(2011, 3, 6) | 1 // one day before endDate
new Date(2011, 3, 7) | 1 // at endDate
new Date(2011, 3, 8) | 0 // one day after endDate
}
}
The Error
groovy.lang.MissingMethodException: No signature of method: static myapp.Event.createCriteria() is applicable for argument types: () values: []
at myapp.EventService.listEventsForDate(EventService.groovy:47)
at myapp.EventServiceSpec.list the Events of a specific date(EventServiceSpec.groovy:29)

You should not use unit tests to test persistence - you're just testing the mocking framework.
Instead, move the criteria query to an appropriately named method in the domain class and test it against a database with an integration test:
class Event {
...
static Set<Event> findAllEventsByDay(Date date, int offset, int max) {
...
}
}
class EventService {
Set<Event> listEventsForDate(Date date, int offset, int max) {
...
return Event.findAllEventsByDay(date, offset, max)
}
}
If there's still value in having the service method as a wrapper (e.g. if it implements some business logic above and beyond the database query), it will now be easy to unit test since it's trivial to mock out the static domain class method call:
def events = [new Event(...), new Event(...), ...]
Event.metaClass.static.findAllEventsByDay = { Date d, int offset, int max -> events }
And that's appropriate since you're testing how the service uses the data it receives and assuming that the retrieval is covered in the integration tests.

Criteria queries are not supported in unit tests. From the mockDomain documentation:
[T]he plugin does not support the mocking of criteria or HQL queries. If you use either of those, simply mock the corresponding methods manually (for example with mockFor() ) or use an integration test with real data.
You'll have to make your test an integration test. You'll see that the exception goes away if you move the test from the test/unit folder to the test/integration folder.
There is some work being done on criteria support in unit tests, and if you're feeling adventurous, you can try it out today. See this mailing list discussion of the DatastoreUnitTestMixin.

Related

Sales force - Test Apex Class List

I made an Apex Class in the Sandbox to call a List.
Now I need to implement it in the production. To do so, I need to implement a Test with at least 75% Success.
The Apex Class produces a List of “dfind_Research_Projekt__c” from which “dfind_Potenzieller_Kandidat__c “ is the actual record, I use this list to make an iteration and show all the “dfind_Research_Projekt__c” on the page from “dfind_Potenzieller_Kandidat__c “.
This is my Apex Class:
public with sharing class dfind_Pot_Job_Application_List {
#AuraEnabled
//Get Pot Job Application List
public static List<dfind_Research_Projekt__c> getJobApp(Id recordId) {
List<dfind_Research_Projekt__c> JobAppList = [Select Id, Name, dfind_Potenzieller_Kandidat__c, dfind_Job__c,
LastModifiedById, dfind_Bewerbungsdatum__c, dfind_Job_Name__c,
OwnerId
from dfind_Research_Projekt__c
where dfind_Potenzieller_Kandidat__c = :recordId
ORDER BY dfind_Bewerbungsdatum__c DESC NULLS LAST];
return JobAppList;
}
//Get User
#AuraEnabled
public static user fetchUser(){
User u = [select id,Name from User where id =: userInfo.getUserId()];
return u;
}
}
This is my test:
#isTest
public class TESTdfind_pot_job_app {
static testMethod void myUnitTest() {
//Create Data for Customer Objet
cxsrec__Potential_candidate__c objKandi = new cxsrec__Potential_candidate__c();
objKandi.Name = 'Test Kandidat';
insert objKandi;
//Create List
List<dfind_Research_Projekt__c> listOfPotApp = new List<dfind_Research_Projekt__c>{
new dfind_Research_Projekt__c(Name='Test Appplication'
, dfind_Job__c='a0w0X000008KKB5QAO'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 1'
, dfind_Job__c='a0w1x0000013aSRAAY'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ'),
new dfind_Research_Projekt__c(Name='Test Appplication 2'
, dfind_Job__c='a0w1x000000JJSBAA4'
, dfind_Potenzieller_Kandidat__c = objKandi.Id
, dfind_Bewerbungsdatum__c = Datetime.now()
, OwnerId= '0050X000007vz5MQAQ')
};
insert(listOfPotApp);
Test.startTest();
// Starts the scope of test
// Now check if it is giving desired results using system.assert
// Statement.New invoice should be created
List<dfind_Research_Projekt__c> JobAppList = new List<dfind_Research_Projekt__c>(listOfPotApp);
Test.stopTest(); // Ends the scope of test
for(Integer i=0;i<JobAppList.Size();i++) {
system.assertEquals(JobAppList[i].dfind_Potenzieller_Kandidat__c,objKandi.Id);
System.debug(i + 'Kandidat: ' + JobAppList[i].dfind_Potenzieller_Kandidat__c + ';');
System.debug(i + ': ' + objKandi.Id + ';');
}
system.assertEquals(1,1);
}
}
The hard-coded Ids in your unit test won't work. Your unit tests executes in an isolated data context and must generate all of its own test data.
As written, this test doesn't really do anything. It does not invoke the code you intend to test, as it must to evaluate its behavior and obtain code coverage. You'd need to call fetchUser() and getJobApp() at some point and write assertions about their return values. The assertions that are currently present are all tautological; they're guaranteed to pass and provide no information.
See How do I write an Apex unit test? on Salesforce Stack Exchange for introductory resources.

Set-up/clean-up only once per feature method with 'where:' block

Spock has setupSpec on the Spec class level. I would want to have something similar for a single test case level.
This might not be available in Spock, Does someone has a workaround for this.
void "test something"() {
setup:
User user = createUser()
when:
user.setAdress(new Address(zipCode: inputZipCode, city: inputCity))
then:
user.address.city == inputCity
user.address.zipCode == inputZipCode
cleanup:
deleteUser(user)
where:
inputCity | inputZipCode
"a" |"1"
"b" |"2"
}
Creating and deleting user is unnecessarily done after every iteration.
Could it be possible to have something la- setupSpec for a single test instead of class-level?
It is possible to manipulate the test cases to use class-setupSpec/CleanupSpec or even create a new test (with #Stepwise) to achieve this but I am looking for something good solution not a hack.
I think this is very ugly because it involves manual bookkeeping. I do not recommend you to do it like this, but anyway:
package de.scrum_master.stackoverflow.q57721328
import spock.lang.See
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
class OneTimeSetupCleanupParametrisedTest extends Specification {
#Shared User user
#Shared int iteration
User createUser() {
// Set up test fixture only if iteration == 0 (or optionally, if fixture is uninitialised)
user ?: new User()
}
void deleteUser(User userInstance) {
// Clean up counter (and test fixture, if any) only if iteration == total number of iterations
if (++iteration == specificationContext.currentIteration.estimatedNumIterations) {
userInstance.delete()
user = null
iteration = 0
}
}
// #Unroll
void "test something"() {
setup:
// Call initialiser helper for each iteration, relying on the fact that it will only
// create a text fixture if none exists yet
user = createUser()
when:
user.setAdress(new Address(zipCode: inputZipCode, city: inputCity))
then:
user.address.city == inputCity
user.address.zipCode == inputZipCode
cleanup:
// Call clean-up helper for each iteration, relying on the fact that it will only
// clean up the fixture during the last iteration
deleteUser(user)
where:
inputCity | inputZipCode
"a" | "1"
"b" | "2"
}
static class User {
Address address
User() {
println "creating user"
}
void setAdress(Address address) {
this.address = address
}
void delete() {
println "deleting user"
address = null
}
}
static class Address {
String zipCode, city
}
}
Console log:
creating user
deleting user
Update: The Spock manual says about this topic:
Sharing of Objects between Iterations
In order to share an object between iterations, it has to be kept in a #Shared or static field.
NOTE: Only #Shared and static variables can be accessed from within a where: block.
Note that such objects will also be shared with other methods. There is currently no good way to share an object just between iterations of the same method. If you consider this a problem, consider putting each method into a separate spec, all of which can be kept in the same file. This achieves better isolation at the cost of some boilerplate code.

Testing criteria creation in a Grails service

I have a Grails service that creates a criteria query with optional parameters like this:
List<Car> search(String make = "%", String model = "%", Integer year = null) {
def c = Car.createCriteria()
return c.list() {
if(make) {
like("make", make)
}
if(model) {
like("model", model)
}
if(year) {
eq("year", year)
}
}
}
(Also, is this the idiomatic way to do this in grails? I'm quite new to the framework and I'm trying to find the right way to do things)
I'd like to test that the proper criteria filters are set according to the values of the parameters of the search method but I'm having no success.
I tried some variations of this:
#TestFor(CarService)
#Mock(Car)
class CarServiceSpec extends Specification {
def car = Mock(Car)
void "empty filters"() {
when: service.search()
then:
with(car.createCriteria()) {
0 * like(*_)
0 * eq(*_)
}
}
}
But I can't seem to find a way to do assertions about the interactions between the CarService and the criteria object.
What am I missing?
The Grails Where query instead of the Criteria query seems to be better choice for an idiomatic way to do this in Grails:
Gorm Where Query

Grails Unit Testing with Composite Keys

I'm trying to unit test a method where an object with a composite key is being inserted into the database. Whenever I run my unit test for this, I get the following.
Failure: |
testTransaction(com.myapp.foo.TestServiceSpec)
|
Condition not satisfied:
Transaction.count() == 1
| |
0 false
at com.myapp.foo.TestServiceSpec.testTransaction(TestServiceSpec.groovy:166)
If I remove the composite key code and nothing else from my domain class, the test passes.
This is my Domain Class, Transaction.groovy:
class Transaction implements Serializable {
String timestamp
String source
String tableName
String fieldName
Integer changeNumber
String fieldValue
String objectId
static mapping = {
id composite: ["timestamp", "source", "tableName", "fieldName", "changeNumber"], generator: 'assigned'
}
boolean equals(other) {
if (!(other instanceof Transaction)) {
return false
}
other.timestamp == timestamp && other.source == source && other.id == id && other.tableName == tableName && other.fieldName == fieldName && other.changeNumber == changeNumber
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append timestamp
builder.append source
builder.append tableName
builder.append fieldName
builder.append changeNumber
builder.toHashCode()
}
}
This is the code that's being tested:
def response = [code: 'OK']
def transaction = new Transaction()
transaction.timestamp = (new Date()).format("yyyy-MM-dd HH:mm:ss.SSS")
transaction.source = "APP"
transaction.tableName = "TABLE_NAME"
transaction.fieldName = "FIELD_NAME"
transaction.fieldValue = "FIELD_VALUE"
transaction.objectId = "OBJECT_ID"
def changeNumber = Transaction.createCriteria().get {
eq("objid", currentTransaction.objid)
eq("tableName", currentTransaction.tableName)
projections {
max("changeNumber")
}
}
currentTransaction.changeNumber = (changeNumber ?: 0) + 1
if(!transaction.save()) {
transaction.errors.each {
println it
}
response = [code: 'error transaction', status: 500]
}
return response
And finally, here's my unit test code:
void testTransaction() {
when:
def response = testService.loadTransaction() // Creates transaction row
then:
assert response == [code: 'OK']
assert Transaction.count() == 1
}
The domain structure was defined by another party, and I can't change it in any way, so the composite key is a must. Unfortunately many classes in this app use composite keys, so if I can't unit test them, a lot of my code can't be covered by unit testing. Any info to get me going in the right direction would be great.
Don't use unit tests to test persistence.
Unit tests have a GORM implementation, but it isn't backed by a database, only a ConcurrentHashMap. It's pretty good, but it should only ever be used to avoid having to mock the persistence layer when unit testing other artifact types like controllers. If you want to test persistence, use a database.
Otherwise, you'll see funky issues like this, and similar issues like false negatives or worse - false positives where a test passes that shouldn't, leaving bugs in your "well-tested" code.

Verify Spock mock with specified timeout

In Mockito there is option to verify if mock method has been called, and specify timeout for this verification (VerificationWithTimeout), for example:
verify(mock, timeout(200).atLeastOnce()).baz();
It there any equivalent to such functionality in Spock?
I was trying to use PollingConditions to satisfy a similar scenario (which wasn't helpful), but instead found satisfaction in Spock's BlockingVariables. To verify that SomeService.method() is invoked at least once in function ClassBeingTested.method() within a given timeout period:
def "verify an interaction happened at least once within 200ms"(){
given:
def result = new BlockingVariable<Boolean>(0.2) // 200ms
SomeService someServiceMock = Mock()
someServiceMock.method() >> {
result.set(true)
}
ClassBeingTested clazz = new ClassBeingTested(someService: someServiceMock)
when:
clazz.someMethod()
then:
result.get()
}
When the result is set, the blocking condition will be satisfied and result.get() would have to return true for the condition to pass. If it fails to be set within 200ms, the test will fail with a timeout exception.
There is no equivalent in Spock. (PollingConditions can only be used for conditions, not for interactions.) The closest you can get is to add a sleep() statement in the then block:
when:
...
then:
sleep(200)
(1.._) * mock.baz()
Using PollingConditions and a boolean variable, the following example evaluates a function until it satisfies an interaction.
def "test the config watcher to reload games if a new customer directory is added"() {
given:
def conditions = new PollingConditions(initialDelay: 1, timeout: 60, factor: 1.25)
def mockGameConfigLoader = Mock(GameConfigLoader)
def gameConfigWatcher= new GameConfigWatcher(mockGameConfigLoader)
boolean gamesReloaded = false
when:
conditions.eventually {
gameConfigWatcher.listenEvents()
assert gamesReloaded
}
then:
1 * mockGameConfigLoader.loadAllGameConfigs() >> {
gamesReloaded = true
}
0 * _
}
This doesn't do exactly what the question asked, but I found it a bit cleaner that using a variable. If you have other conditions to asynchronously test in addition to the interaction, then you can declare the interactions at mock creation time and then use PollingConditions to test the other conditions. PollingConditions will either fail the test or block until the conditions pass, so that by the time the interaction is tested, the method should have been called:
#MicronautTest
class KernelManagerTest extends Specification {
#Inject
KernelManager kernelManager
//create conditions
PollingConditions conditions = new PollingConditions(timeout: 10, initialDelay: 1)
class Exits {
static createKernel (String[] args) {
System.exit(args[0].toInteger())
}
}
def "handles a system exit from within kernel"() {
given:
// set custom kernel
kernelManager.kernelClass = Exits
// create custom logger
kernelManager.log = Mock(Logger) {
1 * warn("Kernel exited unexpectedly.", _ as UnexpectedExitException)
}
when:
// create new kernel (exit 1)
kernelManager.startNewKernel("1")
then:
conditions.eventually {
kernelManager.kernelInstances.size() == 0
kernelManager.kernelThreads.size() == 0
}
}
}