簡體   English   中英

Grails Spock模擬對象

[英]Grails Spock Mocking an Object

我是使用Spock在Grails應用程序中進行單元測試的新手。 但是,我想問以下問題。 可以說我想為以下功能testfun運行測試。

class TestFun{

boolean testfun(long userId, long orderId){

    User user = User.findByUserId(userId)
    if(user == null)return false
    Order order = Order.findByUserAndId(user, orderId)

    HashMap<String, Object> = orderContent   
    orderContent= order.orderContent // the order has an element orderContent for storing the elements that one user orders

    if(orderContent!=null){
      orderContent.put("meal",1)
      order.orderContent = orderContent
      return true
    }

    return false
}
}

在這種情況下,相應的單元測試將是:

class TestFun extends Specification {

    def setup() {

        GroovySpy(User, global: true)
        GroovySpy(Order, global: true)
    }
 def "test funtest"() {

        User user = new User(2).save()
        Order order = new Order(3).save()

        when:
        service.testfun(2,3) == result

        then:
        2*User.findByUserId(2) >> Mock(User)
        1*Order.findByUserAndId(_ as User, 1)>> Mock(Order)
        result == true
}
}

但是,我認為我必須模擬order.orderContent,但我不知道如何模擬它。 現在測試失敗,因為orderContent為null,所以testfun返回false。

有人可以幫我嗎?

這里發生了幾件事,希望對其進行修復將有助於您運行和通過測試。

我不確定,但我相信GroovySpy是一個舊功能,Spock測試中未使用。 而不是使用它來模擬域類,您應該在類定義之前使用@Mock批注,以指定要模擬的域類。

盡管可以模擬域類,但是如果需要進行多次測試,則還需要在setup:塊中或在setup()方法中使用這些對象實際填充內存數據庫。

您提到了創建Mock() ,並使用Spock Mock()方法將創建該對象的模擬,但是您不想將其用於域對象。 它通常用於將手動注入到測試類中的服務類。

保存模擬域類時,我建議您包含參數flush: true, failOnError: true ,這樣,將立即在相應的行中指示失敗的任何驗證。 否則,您可能會在以后的測試中遇到一些奇怪的錯誤。

我不知道您在when:塊中正在做什么,但是when:您不應該使用==進行斷言,而在then:塊中執行所有這些操作。

考慮到所有這些,我認為您的測試類應該看起來像這樣:

@Mock([User, Order])
class TestFun extends Specification {

    def setup() {
        // This object will have an id of 1, if you want a different id, you can either specify it, or create more objects
        User user = new User(first: "john", last: "doe").save(flush: true, failOnError: true)
        new Order(user: user).save(flush: true, failOnError: true)
    }

    def "test funtest"() {

        User user = new User(2).save()
        Order order = new Order(3).save()

        when:
        boolean result = service.testfun(1, 1)

        then:
        // Optionally you can just use "result" on the next line, as true will be assumed
        result == true
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM