Reputation: 1089
I am trying to do a unit test on the list action of a controller. Here is the code for testing it :
void testListAction()
{
ac = new AddressesController();
def org = new Organizations(viewAllPost: true);
mockForConstraintsTests(Addresses);
def a = new Addresses(firstLine:'A', secondLine:'B', thirdLine:'C', luCountry:UnitedStates, zipCode:'12345', luState:Florida, city:'jag');
assertTrue(a.validate());
mockSession['currentUserOrganizationId'] = org;
mockDomain(Addresses, [
new Addresses(firstLine:'A1', secondLine:'B', thirdLine:'C', luCountry:UnitedStates, zipCode:'12345', luState:Florida, city:'jag'),
new Addresses(firstLine:'A2', secondLine:'B2', thirdLine:'C2', luCountry:UnitedStates, zipCode:'12344', luState:Florida, city:'jag2')
]);
def model = ac.list();
assertEquals(2, model.postInstanceList.size());
}
But No matter how I tried I am always getting back the same result that the model.postInstanceList is null and I can not invoke the size method on it. What am I doing wrong here ?
Upvotes: 0
Views: 1109
Reputation: 360
You are not saving the instances. You should save:
mockDomain(Addresses)
new Addresses(firstLine:'A1', secondLine:'B', thirdLine:'C', luCountry:UnitedStates, zipCode:'12345', luState:Florida, city:'jag').save()
new Addresses(firstLine:'A2', secondLine:'B2', thirdLine:'C2', luCountry:UnitedStates, zipCode:'12344', luState:Florida, city:'jag2').save()
I would do it like this:
mockDomain(Addresses)
mockForContraintsTests(Addresses)
def address1 = new Addresses(firstLine:'A1', secondLine:'B', thirdLine:'C', luCountry:UnitedStates, zipCode:'12345', luState:Florida, city:'jag')
if(address1.validate()) address1.save()
def address2 = new Addresses(firstLine:'A2', secondLine:'B2', thirdLine:'C2', luCountry:UnitedStates, zipCode:'12344', luState:Florida, city:'jag2')
if(address2.validate()) address2.save()
assertEquals 2, Addresses.list().size()
Upvotes: 1
Reputation: 3243
You're accessing the model incorrectly. In a unit test you should access the model via:
def model = controller.modelAndView.model
Then access whatever you want off of the model so in your instance it would be:
ac.list()
def model = ac.modelAndView.model
assertEquals(2, model.postInstanceList.size())
Upvotes: 2