Grails中的单元测试控制器

时间:2012-01-03 16:14:00

标签: grails gorm

我正在尝试对控制器的列表操作进行单元测试。以下是测试它的代码:

  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());
   }

但无论我如何尝试,我总是得到与model.postInstanceList为空的相同结果,我无法在其上调用size方法。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您正在错误地访问模型。在单元测试中,您应该通过以下方式访问模型:

def model = controller.modelAndView.model

然后从模型中访问任何你想要的东西,所以在你的实例中它将是:

ac.list()
def model = ac.modelAndView.model
assertEquals(2, model.postInstanceList.size())

答案 1 :(得分:1)

您没有保存实例。你应该保存:

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()

我会这样做:

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()