如何模拟ProceedingJoinPoint

时间:2014-12-24 11:49:56

标签: java unit-testing aspectj spock

我正在尝试编写测试AspectJ建议类的Spock规范。因此,我需要一个org.aspectj.lang.ProceedingJoinPoint类的模拟实例。

void "Verify client capability mechanism"() {

   given:
   def pointCut = Mock(ProceedingJoinPoint)

   and: 'the method calls would have the following arguments'
   pointCut.getArgs() >> ['xxx', 1L, 44] as Object[] // this is where the error happens

   when: 'the advice gets called'
   def retVal = new ClientCapabilitySecurityAdvice().verifyUserCanPerformActionOnCurrentClient(pointCut)

   then: 'the call may proceed'
   1 * pointCut.getArgs()
   1 * pointCut.proceed() >> 'Hello'
   retVal == 'Hello'
}

由于某种原因,我无法在我的模拟实例上的getArgs()上定义返回值。我收到此错误消息。

java.lang.NullPointerException: Cannot invoke method rightShift() on null object

模拟ProceedingJointPoint界面的正确方法是什么?有人可以帮我吗?

PS:祝你圣诞快乐:)

更新(根据彼得解决方案)

void "Verify client capability mechanism"() {                                                            

    given:                                                                                               
    def pointCut = Mock(ProceedingJoinPoint)                                                             

    when: 'the advice gets called'                                                                       
    def retVal = new ClientCapabilitySecurityAdvice().verifyUserCanPerformActionOnCurrentClient(pointCut)

    then: 'the method calls would have the following arguments'                                          
    1 * pointCut.getArgs() >> ['xxx', 1L, 44]                                                            

    and: 'the actual return value is set'                                                                
    1 * pointCut.proceed() >> 'Hello'                                                                    

    and: 'the call may proceed'                                                                          
    retVal == 'Hello'                                                                                    
}  

1 个答案:

答案 0 :(得分:0)

我可以发现两个错误:

  1. pointCut.getArgs() >> ['xxx', 1L, 44] as Object[](pointCut.getArgs() >> ['xxx', 1L, 44]) as Object[]相同,不是模拟互动。要解决此问题,您需要在RHS上使用parens。可能你甚至可以省略强制,因为Groovy会自动完成。

  2. 同一个方法调用的存根和模拟需要在同一个语句中进行:then: 1 * pointCut.getArgs() >> (['xxx', 1L, 44] as Object[])。有关详细信息,请参阅http://docs.spockframework.org的模拟章节。