[英]Grails Criteria not working in JUnit Test
I'm trying to test search method in my grails app but I'm having a null pointer exception. 我正在尝试在grails应用程序中测试搜索方法,但是我遇到了空指针异常。 I mocked the domain in my test as follows: 我在测试中模拟了域,如下所示:
@TestFor(AuditController)
@Mock(Audit)
class AuditControllerTests {
void testSearch() {
populateValidParams(params)
def audit=new Audit(params)
audit.save(failOnError: true)
//Search existing customer
def model = controller.search()
assert model.auditInstanceList.size() == 1
assert model.auditInstanceList.size() == 1
}
}
I got NPE on model.auditInstanceList. 我在model.auditInstanceList上获得了NPE。 Where it shouldn't be null. 不应该为null的地方。 Here is the code in my controller: 这是我的控制器中的代码:
def search = {
def query
def criteria = Audit.createCriteria()
def results
query = {
and{
if(params.customerName){
ilike("customerName", params.customer + '%')
}
if(params.siteName){
ilike("siteName", params.siteName + '%')
}
max:params.max
offset:params.offset
}
}
results = criteria.list(params, query)
render(view:'list', model:[ auditInstanceList: results,auditInstanceTotal:results.totalCount ])
}
What is going on with this? 这是怎么回事?
I don't know why but sometimes you need to remove model as a return value from controller's action. 我不知道为什么,但是有时您需要从控制器的操作中删除模型作为返回值。 I use both version alternatively in case one of them fails: 如果其中一个失败,我会同时使用两个版本:
// sometimes this one works
def model = controller.search()
assert model
// sometimes this one works
controller.search()
assert model
Edit: I think of two new possibilities why your action doesn't work: 编辑:我想到了两种新的原因导致您的操作无效:
Return model
at the end of search
. 在search
结束时返回model
。 As in, 如
def search = {
...
render(view:'list', model:[ auditInstanceList: results, auditInstanceTotal:results.totalCount ])
[auditInstanceList: results, auditInstanceTotal:results.totalCount]
}
When testing a controller action that calls render()
, model
and view
variables are automatically created and populated in your test. 测试调用render()
的控制器动作时,将自动创建model
和view
变量,并在测试中填充该变量。 By doing def model = controller.search()
, you are replacing the magic model
with your own, assigning it to the return value of search()
. 通过执行def model = controller.search()
,您将用自己的魔术model
替换魔术model
,并将其分配给search()
的返回值。 The correct way to do your assertions is: 做出断言的正确方法是:
controller.search()
assert model.auditInstanceList.size() == 1
assert view == '/audit/list'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.