如何模拟控制器内部的Command对象 [英] How to Mock Command Object that is inside Controller
问题描述
我有一个控制器类,其中有一个命令对象。我有一个方法find()使用这个命令对象如下:
class itemController {
// command object
class SearchCommand {
String email
static constraints = {
email blank:false,email:true
}
def find = {SearchCommand sc - >
if(!sc.hasErrors()){
----- do something ---
}
}
现在,我编写一个测试用例来测试控制器中的find方法。但是测试用例失败了
if(!sc.hasErrors())
因为sc仍为'null'。我不知道如何处理这个内部类命令对象在测试用例。
我写的测试用例是:
class itemControllerTests extends ControllerUnitTestCase {
pre>
void testFind(){
def model = controller.find()
assertNotNull(model)
}
}
如何处理测试用例中的内部类Command Object。我模拟吗?我试过使用mockCommandObject(?),但不知道我应该如何将内部类命令对象传递给此?
解决方案可以使用mockCommandObject
类RioController
class RioController {
class UserCommand {
String email
static constraints = {
email blank:false,email:true
}
}
def load = {UserCommand cmd - >
if(cmd.validate()){
flash.message =Ok
}
else {
flash.message =电子邮件在哪里?
}
}
}
类RioControllerTests
import grails.test.mixin。*
import org.junit。*
@TestFor )
class RioControllerTests {
@Test
void testLoad(){
mockCommandObject RioController.UserCommand
controller.load()
assert flash .message ==电子邮件在哪里?
params.email =verynew@email.com
controller.load()
assert flash.message ==Ok
}
}
I have a controller class, inside of which i have a command object. I have a method find() which uses this command object as follows:
class itemController{ //command object class SearchCommand{ String email static constraints={ email blank:false,email:true } def find = {SearchCommand sc -> if(!sc.hasErrors()){ ----- do something--- } }
Now, I am writing a test case to test the find method in the controller. But the test case fails at
if(!sc.hasErrors())
as sc is still 'null'. I am not sure how to handle this inner class command object in the test case. The test case that i have written so far is:
class itemControllerTests extends ControllerUnitTestCase { void testFind(){ def model = controller.find() assertNotNull(model) } }
How do I handle the inner class Command Object in the test case. Do I mock it? I have tried using mockCommandObject(?), but not sure how should i pass the inner class command object to this?
解决方案You can use mockCommandObject
Class RioController
class RioController { class UserCommand{ String email static constraints = { email blank: false, email: true } } def load={UserCommand cmd -> if(cmd.validate()){ flash.message = "Ok" } else{ flash.message = "Where is the email?" } } }
Class RioControllerTests
import grails.test.mixin.* import org.junit.* @TestFor(RioController) class RioControllerTests { @Test void testLoad(){ mockCommandObject RioController.UserCommand controller.load() assert flash.message == "Where is the email?" params.email = "verynew@email.com" controller.load() assert flash.message == "Ok" } }
这篇关于如何模拟控制器内部的Command对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!