在 Spock 测试中访问方法内部的变量

Access variables inside methods in a Spock Testing

在 Spock 测试中,我希望能够更改方法内变量的值。
例如,我想将 uName 的值更改为 'John'。或者对于另一个测试,在进行测试时将 uCat 的值更改为 "seller" 。我如何确保在测试中执行 else 语句中的 2 个方法:postComment 和 sendEmails。

class userService {

    void userComment()
    {
        def uName = "test123"   
        def uCat = Category.getUserCategory(uName)

        if (uCat.empty){    
            println("no categories to process")
        }
        else
        {
            postComment(uName)
            batchJob.sendEmail(uName)   
        }
    }
}



class userServiceSpec extends Specification{
    def "test userComment"()
    {   
        given:
        ?????

        when:   
        ?????

        then:
        1 * postComment(_)

        then:
        1* batchJob.sendEmail(_)
    }
}

对于uName,您需要将用户名作为构造函数参数注入或在您的服务中添加方法参数。方法参数可能最有意义。

因为您将 getUserCategory 设为静态方法,所以您必须使用 GroovySpy 但这通常表明您做错了什么。你真的应该制作一个 CategoryService 注入你的 userService

class userService {

    void userComment(uName)
    {  
        def uCat = Category.getUserCategory(uName)

        if (uCat.empty){    
            println("no categories to process")
        }
        else
        {
            postComment(uName)
            batchJob.sendEmail(uName)   
        }
    }
}


class userServiceSpec extends Specification{
    def userService = Spy(userService)
    def CategorySpy = GroovySpy(Category, global: true)

    def "test userComment"()
    {   
        given:
        def uName = "test123"  

        when: 'we have a category found'  
        userService.userComment(uName)

        then: 'return user cat of "seller" '
        1 * CategorySpy.getUserCategory(uName) >> 'seller'
        1 * postComment(uName)

        then:
        1 * batchJob.sendEmail(uName)

        when: 'we have an "empty" category'  
        userService.userComment(uName)

        then: 'return a category where uCat.empty will be true'
        1 * CategorySpy.getUserCategory(uName) >> []
        0 * postComment(uName)
        0 * batchJob.sendEmail(uName)
    }
}

一些Spock Framework slides可能有帮助

综上所述,您真的应该重构以使您的 classes 更易于测试。依赖注入是你的朋友。永远不要像那样在 class 中硬编码值。