我想單元測試控制器的顯示動作。它的定義是:單元測試顯示一個控制器在grails中找到的地方
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到控制器的PARAMS對其進行測試。但測試沒有通過。
此外,我試圖在我的單元測試方法上測試findWhere方法,無論我給它什麼參數,它都會說missingMethodException,對於給定的數據類型不存在這樣的簽名。我完全卡住了。這裏是我的測試代碼:
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);
}
我已經嘗試了大部分的東西,但只是無法解決它。我錯過了什麼?謝謝。
無關的,但'Addresses.findWhere(ID:的Long.parseLong(params.id));'是太冗長;只是使用'Addresses.get(params.id)',因爲它是等價的,並將參數轉換爲正確的類型 – 2012-01-04 23:45:10
哦,上帝是的,這是正確的。但它是我只能測試而不是改變的代碼。傷心。 – 2012-01-05 00:07:38
你的測試失敗了嗎?它在控制器中的測試或Address.findWhere(..)中位於a1.save()中? – 2012-01-05 14:19:39