Grails Model Unity Test - grails

I have a "domain"(model) that want to do an Unity Test to check if works.
But when I execute the test I get
java.lang.IllegalArgumentException: Test class can only have one constructor
Thats always happen when trying to initialize a class of some domain(model).
What would be the approach to do correctly the testcase?
class Race {
static constraints = { }
String name
Date startDate
String city
String state
BigDecimal distance
BigDecimal cost
Integer maxRunners = 100000
BigDecimal inMiles() {
return 0.6
}
}
And in the Unity Test Class
import grails.test.mixin.TestFor
import spock.lang.Specification
#TestFor(Race)
class RaceTest extends Specification {
void testInMiles() {
when:
def model = new Race(distance:5.0);
then:
0.6 == model.inMiles()
}
}

In Grails 2.4.x (which is what I'm assuming you're using) the default test type is a Spock test, and that's what's created by the generate-* scripts. You can still write your own tests in JUnit 3 or 4 style if you prefer. But test classes in Spock (at least using the Grails integration, I'm not sure if it's as strict outside of Grails) have to have names ending in "Spec". That's why you're seeing that error.
Test methods do not have to be void and start with "test" (JUnit 3 style) or be void and have an #Test annotation (JUnit 4 style). The test runner decides if a method is a test method if it's public (either explicitly or if there's no scope modifier) and there's at least one labelled block, e.g. when:, given:, then:, etc. Further, Spock uses some AST magic to allow you to use spaces in method names (you just have to quote the whole name) and have expressive, self-descriptive method names, e.g.
def 'an admin without ROLE_SUPER cannot view records of other admins'() {
...
}

Related

Map constructor does not assign String to Object in Grails

Given the following domain class:
class Dog {
Object name // changing the type to String fixes it
}
And this unit test:
import grails.test.mixin.Mock
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.*
/**
* See the API for {#link grails.test.mixin.support.GrailsUnitTestMixin} for usage instructions
*/
#TestMixin(GrailsUnitTestMixin)
#Mock([Dog])
class DogSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "test something"() {
Dog dog = new Dog(name:"sparky")
// dog.name = "sparky" // adding this line also fixes it
expect:"fix me"
dog.name == "sparky"
}
}
Running grails test-app fails, but if you change the type of Dog.name to String, it works fine. Debugging brings me to realize that Dog.name never gets assigned and is null. If I were to set dog.name via regular assignment after constructing it as above, the test passes.
This issue does not occur in Groovy Script using the same map constructor assignment.
I want my type to be Object as it varies depending on the use case.
Any idea why this is happening? Is it a bug in Grails?
I did some debugging and I found out that when a field accepts an Object, grails framework doesn't do databinding on this property.
More specifically, the Dog#name field doesn't belongs to the whitelist of properties when It is declared as Object.
That's why this doesn't work.
If you want to debug, see the
grails.web.databinding.DataBindingUtils#getBindingIncludeList(final Object object)
If you put a breakpoint there, you will see how grails generates the whitelist of properties.
I think this makes a lot of sense since It's related to security!
See more about it here
If you wanna bind on an Object field nevertheless, this code may help you:
class Dog {
Object name
static constraints = {
name(bindable: true)
}
}

Programmatically skip a test in Spock

How do I programmatically skip a test in the Spock framework? I know I can annotate a test with #Ignore to skip it, or use #IgnoreIf to skip tests based on environmental variables and the like. But is there a way to run arbitrary code that decides whether or not a test should run?
For example, let's say I have an integration test that has to connect to a third-party service's sandbox environment. Outages in the service's sandbox environment cause the test to fail. Assuming I've written a method canConnectToService that checks if the test will be able to connect to this service, how do I write a test that will be skipped if canConnectToService() returns false?
Use JUnit's Assume class. Specifically, you could write Assume.assumeTrue(canConnectToService()) at the beginning of your test to skip the test if the third party service is unavailable. This method will throw an AssumptionViolatedException if canConnectToService() returns false, and Spock ignores tests that are interrupted by an AssumptionViolatedException for JUnit compatibility (see this bug report).
There is another alternative (maybe it didn't exists before):
Using instance inside #Requires or #IgnoreIf:
Examples using inheritance, but not required:
abstract class BaseTest extends Specification {
abstract boolean serviceIsOnline()
#Requires({ instance.serviceIsOnline() })
def "some test" () { .. }
}
SubSpecification:
class OnlineTest extends BaseTest {
boolean serviceIsOnline() {
// Test connection, etc.
return true
}
}
class SkipTest extends BaseTest {
boolean serviceIsOnline() {
return false
}
}
Documentation
instance
The specification instance, if instance fields, shared
fields, or instance methods are needed. If this property is used, the
whole annotated element cannot be skipped up-front without executing
fixtures, data providers and similar. Instead, the whole workflow is
followed up to the feature method invocation, where then the closure
is checked, and it is decided whether to abort the specific iteration
or not.
As an extra, another way you can programmatically skip a test is using the where label:
class MyTest extends Specification {
List getAvailableServices() {
// You can test connections here or your conditions
// to enable testing or not.
return available
}
#Unroll
def "Testing something"() {
setup:
URL url = serviceUrl.toURL()
expect:
assert url.text.contains("Hello")
where:
serviceUrl << availableServices
}
}

Grails integration test cannot invoke method on null service object?

Simple service class, AnalyzerService, calls stored proc in a database.
Attempting to run integration test to ensure service calls the stored proc and correct data is returned after analyzer class operates on it. However, getting the dreaded exception that "Cannot invoke method calculateEstimateNumberOfPositions() on null object". Why is the service object null? What am I missing?
THANK YOU!
package foobar.analyze
import static org.junit.Assert.*
import org.junit.*
import foobar.analyze.AnalyzerService
//#TestFor(AnalyzerService)
class AnalyzerServiceTests {
def AnalyzerService service
def dataSource
#Before
void setUp() { }
#After
void tearDown() { }
#Test
void testcalculateEstimateNumberOfPositions() {
String positionName = "crew"
String city = "Great Neck"
String state = "NY"
int numberOfPositionsSought = 100
int expectedNumberOfPositionsEstimate = 100
def numberOfPositionsEstimate = service.calculateEstimateNumberOfPositions(positionName, city, state, numberOfPositionsSought)
fail (numberOfPositionsEstimate != expectedNumberOfPositionsEstimate)
}
}
Convention. Stick to the convention. Anything out of convention, regarding nomenclature, will create problem during dependency injection.
Convention is to use the service class name as analyzerService instead of service in integration test.
The integration test should look like
class AnalyzerServiceTests extends GroovyTestCase {
//Service class injected only if you
//use the naming convention as below for AnalyzerService
def analyzerService
def dataSource
......
......
}
It was possible to use service in unit test case when you use the test mixin
#TestFor(AnalyzerService)
By using the above in unit test cases, you could use the default service variable in the test cases. This is not the same in case of integration tests.

Changing autoGenerating Grails Test Scaffold to Spock Test

Hi i m trying to change the auto-generated testCases in grails
#TestMixin(GrailsUnitTestMixin)
class KLAKSpec {
void setUp() {
// Setup logic here
}
void tearDown() {
// Tear down logic here
}
void testSomething() {
fail "Implement me"
}
}
to Spock Type test format which is something like this
#TestFor(GrailsUnitTestCase)
class #artifact.name# extends #artifact.superclass# {
def "feature method"() {
setup:
when:
then:
where:
}
}
Althought i have added a _Events.groovy script under the scipt folder and added a Spec.groovy file in artifacts folder which changes the name when i auto generate the list.
Can any one please let me knw how i can change to spec format.
I wrote a blog post on this some time ago: Auto-generate Spock specs for Grails artifacts. The post was written pre-Grails 2 so it's still using the old superclasses rather than #TestFor but it should be easy enough to adapt. We still use this technique on our project where we're still on Grails 1.3.7. It's a bit of a blunt instrument as Grails doesn't expose a unique event for test generation but it works fine.

Grails - save() failing with MissingMethodExcepition in integration test

I'm learning groovy / grails, and writing my first integration test.
It's currently failing with:
groovy.lang.MissingMethodException: No
signature of method:
com.mangofactory.scurry.User.save() is
applicable for argument types: ()
values: []
My test isn't doing anything fancy:
class UserEventControllerTests extends ControllerUnitTestCase {
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
void testAddingAUser()
{
def user = new User(emailAddress: "martypitt#test.com")
user.save()
}
}
Saving the entity works fine when I do it through the scaffolded pages provided by grails.
What have I missed?
If you want it to be an integration tests it shouldn't extend one of the unit test base classes, so change it to
class UserEventControllerTests extends GroovyTestCase {
...
}
and make sure it's in test/integration, not test/unit.
But it looks like you want to test a controller (it's called UserEventControllerTests) which should extend ControllerUnitTestCase. If that's the case then you should be doing unit tests, but mocking the domain layer (using mockDomain and others) since you want to focus on controller logic, not persistence. Test domain classes in proper integration tests using a database.
This is all described in chapter 10 of the docs: http://grails.org/doc/latest/

Resources