开发者

Remove Domain Class Dependency from Controller Unit Test

开发者 https://www.devze.com 2023-02-16 12:30 出处:网络
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

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消