mardi 13 septembre 2016

Spock Testing and mocking or stubing database interaction

I have a private controller method that is used by multiple actions to retrieve an object from the database. I can not for the life of me correctly mock/stub the call to the database. The Controller method is:

private Order getSalesOrder(){
       def order = Order.get(params.id)
       if(!order){
          flash.message = (code: 'default.not.found.message', args: [message(code: 'order.label', default: 'Order'), params.id])
          redirect action: "list"
          return
       }
       return order
 }

The Test method I have at this point is:

def "test getSalesOrder returns Sales Order"(){
    given:
    params.id >> 3002L

    criteriaSetup()
    Order testOrder = salesOrders[2]
    Order.metaClass.static.get() >> testOrder

    when:
    def order = controller.getSalesOrder()

    then:
    1 * Order.get(3002) >> testOrder
    //1 * Order.get() >> salesOrders[2]
    order == testOrder

}

My results are either a message about too few invocations or I just get a null value back. Both of which cause the test to fail.

I have tried variations of this by using examples found from various blogs or tutorials such as:

Order.metaClass.static.get() >> testOrder
Order.metaClass.methods.get = { return testOrder } 
1 * Order.get(3002) >> testOrder
1 * Order.get(params.id) >> testOrder

I'm not sure where to go from here, since I'm new to spock tests, Mocking and Stubing in general. And due to the fact that we are writing test for legacy code it is even more confusing.

Aucun commentaire:

Enregistrer un commentaire