I have a controller that is supposed开发者_如何转开发 to operate on domain classes in my application but that does not care what type of domain class it is working with. I'd like to write unit tests to verify that it responds correctly but I don't want to couple it to a domain class in my application in case the domain class changes or is removed. Something like this:
void testReadNoItems() {
mockDomain(Item)
controller.params["class"] = "DefaultGrailsDomainClass"
controller.params.xaction = "read"
controller.index()
def json = JSON.parse(controller.response.contentAsString)
assert json.metaData.root == "data"
assert json.metaData.totalProperty == "total"
assert json.metaData.successProperty == "success"
assert json.metaData.idProperty == "id"
assert json.metaData.fields[0].id == "int"
assert json.metaData.fields[1].name == "string"
assert json.data == []
assert json.total == 0
}
Is there any way to remove the dependency on the Item domain class?
If you remove all references of Item
from the controller, you can create an ItemService
(which is transactional) and inject it into the controller. From there, you can keep the ItemService
relatively fixed and mock it in the controller.
Test:
protected void setUp(){
controller.itemService = [retrieveItems: { arg -> return [new Item()] }] as ItemService
}
精彩评论