帮助我了解如何使用JUnit
模拟控制器内的服务方法,以便在grails中进行单元测试我试图为我的控制器写一个单元测试用例"添加"。
void testAdd_UT_03(){
......declaring and assigning prerequisites
controller.add() // This is the controller i want to unit test
.... asserting
}
//控制器 def add {
def a =someService.method()
}
在内部控制器中,调用了一些服务方法,而这些方法又使用了HQL语句。由于我无法在单元测试中找到处理HQL语句的方法,我想模拟服务方法本身。 (我希望服务方法返回预定义的输出)。 有人可以解释一下如何实现这个目标吗?
你能解释一下何时使用mockController吗?通过嘲笑我们真正实现的目标是什么? (我得到真实的画面,因为我对此完全陌生)
提前致谢, BK
答案 0 :(得分:2)
您可以在测试的setUp方法中添加以下代码来模拟服务方法,并在调用方法时添加"添加"控制器上的方法将调用模拟的服务方法。
def predifinedOutput
void setUp(){
def mockControl = mockFor(YourService)
//params are the parameters passed to the service method
mockControl.demand.yourServiceMethod(0..10) { params->
predifnedOutput = "predifinedOutput"
return "predefined output"
}
controller.yourService = mockControl.createMock()
}