当前位置: 首页 > 知识库问答 >
问题:

定义Spock模拟行为

丌官积厚
2023-03-14
class MyRealmSpec extends Specification {
    MyRealm realm

    def setup() {
        AuthService authService = Mock(AuthService)
        // configure 'authService' mock  <-- ?????

        ShiroAdapter shiroAdapter = new ShiroAdapter()

        realm = new MyRealm(authService: authService, 
            shiroAdapter: shiroAdapter)
    }

    def "authenticate throws ShiroException whenever auth fails"() {
        when:
        realm.authenticate('invalid_username', 'invalid_password')

        then:
        Throwable throwable = thrown()
        ShiroException.isAssignableFrom(throwable)
    }
}

这里,myrealm#authenticate(String,String)在引擎盖下调用authservice#doauth(String,String)。因此,我需要我的模拟AuthService实例返回false(指示失败的auth),或者在发生意外情况时抛出ServiceFaulException

你知道我该怎么做吗?

共有1个答案

邓翼
2023-03-14

您非常接近,检查抛出的异常类型的一个简单、快捷的方法是将exception类放在括号中。例如:

def "authenticate throws ShiroException whenever auth fails"() {
    when:
    realm.authenticate('invalid_username', 'invalid_password')

    then:
    thrown(ShiroException)

}

您还需要模拟LDAP服务调用本身,并模拟异常或登录失败。模拟操作放在测试的then子句中。

def "authenticate throws ShiroException whenever auth fails"() {

    setup:
    String invalidUserName = 'invalid_username'
    String invalidPassword = 'invalid_password'

    when:
    realm.authenticate(invalidUserName, invalidPassword)

    then:
    1 * authService.doAuth(invalidUserName, invalidPassword) >> returnClosure  
    thrown(ShiroException)

    where:
    returnClosure << [{throw new ShiroException()}, { false }]
}

请注意,您需要使模拟语句上的参数匹配或使用通配符匹配。

1 * authService.doAuth(_, _) >> false
 类似资料:
  • 我不明白为什么不能将模拟的预定义行为移到and:块中。

  • 我有一个用注释的Groovy类,因此它得到一个私有的最终字段,我想测试它的用法。我想继续使用,而不是为了启用测试而进一步公开字段。 我正在使用Spock1.0编写测试,并尝试使用Spock的集成、模拟和截尾功能来完成测试。全局截尾可以帮助我截取调用以获得实际的实例,因此我目前的猜测是: 有趣的是,拦截实际上起作用了,确认类实际上获得了名为“dummy”的类型“logger”的对象

  • 我在micronaut中有以下接口来执行HTTP POST请求: 我有一个调用接口的类: 我想在我的spock测试中模拟/存根API调用,我尝试了以下方法: 然而,我得到的错误:

  • 我用代码编写了以下旧方法,用于访问服务类中的请求对象,例如:

  • 我在StackOverflow和Google上搜索了一段时间,试图找到能够在Spock规范中运行此代码的正确配置/语法: 然而,当我运行单元测试时,cglib向我抛出了一个令人讨厌的异常: 我看了这个问题/答案--用Stock中的GroovyMock或类似的方法模拟静态方法--希望它能给我一个好的起点,但是在我的例子中被模拟的类groovy.sql是一个groovy类,所以我不确定它是正确的起点。