单元测试显示控制器的动作,其中包含grails中的find

时间:2012-01-04 23:26:47

标签: unit-testing grails groovy

我正在尝试单元测试显示控制器的动作。它的定义是:

def show = {
        //scs 11/22/2011 limit access to users in their Organization
        def currentOrgViewCheck = session.currentUserOrganizationId.viewAllPost;
        def currentOrg = session.currentUserOrganizationId;

        def addressesInstance ;
        if(currentOrgViewCheck){
            addressesInstance = Addresses.findWhere(id:Long.parseLong(params.id));
        }else{
            addressesInstance = Addresses.findWhere(id:Long.parseLong(params.id), organization:currentOrg);
        }


        if (!addressesInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'addresses.label', default: 'Addresses'), params.id])}"
            redirect(action: "list")
        }
        else {
            [addressesInstance: addressesInstance]
        }
    }

我试图通过模拟地址域来测试它,然后创建并保存一个地址实例,最后将它的id传递给控制器​​的参数。但是测试没有通过。
此外,我尝试在我的单元测试方法上测试findWhere方法,无论我给它什么参数,它继续说missMethodException,对于给定的数据类型不存在这样的签名。我完全陷入困境。这是我的测试代码:

void testShowFound()
   {
       // New Controller to test
       ac = new AddressesController();

       // this instance is required both to test as well as a session variable
       Organizations org = new Organizations(name:'test', phone: '352-999-8888', createdBy: creator, modifiedBy: modifier, viewAllPost: true);
       org.save();

       //Create an address to pass its id to the action as parameter.
       Addresses a1 = new thlc.Addresses(firstLine:'A1', secondLine:'B', thirdLine:'C', luCountry:UnitedStates, zipCode:'12345', luState:Florida, city:'jag');
       a1.save();   

       ac.metaClass.getParams = {->[id:a1.id] }
       //ac.params.id = a1.id; // I tried both ways.



        // This findWhere is giving error, can any one explain why ?
       //def a = Addresses.findWhere(id:a1.id);
       //assertEquals(a, a1);

       //session variables mocked.
       mockSession['currentUserOrganizationId'] = org;

       // This is to bypass the flash message problem, cause it is not possible to
       // mock the message method on flash messages.
       //ac.metaClass.message = { Map map -> return "ByPass Message" }

       //Call the action and test
       def model = ac.save();
       assert(model);

       //Testing redirect, This is the test that is failing
       assertEquals("list", redirectParams.action);
   } 

我已经尝试了大部分的事情,但只是无法解决它。我错过了什么?感谢。

1 个答案:

答案 0 :(得分:0)

似乎在Grails 1.3.7(及以下)mockDomain中没有创建findWhere()动态查找程序。从它的声音中你必须自己模拟方法,如果你想使用它。我自己还没有这样做。

参考文献:

http://www.slideshare.net/tlberglund/test-first-refresh-second-testdriven-development-in-grails(幻灯片38)

http://grails.1312388.n4.nabble.com/New-approach-to-mocking-domain-classes-in-Grails-unit-tests-td2529895.html