Reputation: 51
I need a little help in writing Unit tests for my project. I have created Unit test classes for my Controllers and Domain.
My Question is- I have a domain class named employee It has- String id String firstname String middleInitial String lastname String status String empType String userid
And I want to mock them in my setUp() method under test class EmployeeControllerTest()
package EmployeeController
import static org.junit.Assert.*
import grails.test.mixin.*
import grails.test.mixin.support.*
import org.junit.*
import java.io.Serializable
import grails.test.mixin.TestFor
import grails.test.mixin.TestMixin
import grails.test.mixin.Mock
import grails.test.mixin.support.GrailsUnitTestMixin
import grails.test.mixin.domain.DomainClassUnitTestMixin
import grails.test.mixin.services.ServiceUnitTestMixin
import grails.test.mixin.web.ControllerUnitTestMixin
import grails.test.mixin.web.FiltersUnitTestMixin
import grails.test.mixin.web.GroovyPageUnitTestMixin
import grails.test.mixin.web.UrlMappingsUnitTestMixin
import grails.test.mixin.webflow.WebFlowUnitTestMixin
@TestMixin(GrailsUnitTestMixin)
@TestFor(EmployeeController)
@Mock([Employee])
class EmployeeControllerTests {
void setUp() {
// Setup logic here
def Employee ce = new Employee()
ce.put(empNo: "001", firstname: "amy", middleInitial: "ratr", lastname: "suz", status: "A", empType: "vendor", userid: "amar")
}
void tearDown() {
// Tear down logic here
}
void testSomething() {
//fail "Implement me"
}
Kindly, let me know if I am missing something or need to do some modifications.
Thanks in Advance :) Amy
Upvotes: 1
Views: 4732
Reputation: 50245
Your Unit Test case can be reduced to few lines of code:
package EmployeeController
import org.junit.*
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
@TestFor(EmployeeController)
@Mock(Employee)
class EmployeeControllerTests {
void setUp() {
def ce =
new Employee(empNo: "001", firstname: "amy",
middleInitial: "ratr", lastname: "suz",
status: "A", empType: "vendor",
userid: "amar").save(flush: true)
}
}
@TestFor
mixin takes care of the contoller mocking. You can very well access some keywords here like controller
, contoller.params
, controller.request
, controller.response
without instantiating controller.
@Mock
is responsible for mocking the domain class Employee
.
Upvotes: 1
Reputation: 911
you shouldn't use @TestMixin
together with @TestFor
because TestMixin comes from the old unit testing stuff from grails 1.3 - I suggest removing it
Upvotes: 4