0

在我的代码中,我有两个类,一个称为 DynamicRule,另一个称为 AORule 的包装器,它为规则实例提供 GPARS activeObject 包装器。

DynamicRule 看起来有点像这样 - 使用一个名为 dynamicExecute 的方法

@InheritConstructors
@Component
@Slf4j  //use Groovy AST to get logger
@EqualsAndHashCode
@Scope ("prototype")       //IOC to deliver new instance on each injection
@Qualifier ("dynamicRule")

class DynamicRule extends BasicRule implements org.easyrules.api.Rule {

    Closure dynamicEvaluation = null
    Closure dynamicExecution = null
    String  sync = "sync"
... with method 
void dynamicExecute () {
    log.debug "dynamic execute: " + this.dump() +  " : dynamic execute called : a rule.dynamicExecution was defined as > " + this.dynamicExecution
    //if dynamic execution closure defined then call that
    log.debug "dynamic execute: getting DynamicExecution reference "
    def clos = this.getDynamicExecution()
    //assert clos == this.dynamicExecution
    log.debug "dynamic execute: rule.dynamicExecution using get() returns " + clos.dump()
    if (clos) {
        clos.call()  //call execute action
        log.debug "dynamic execute: dynamic rule closure  was executed "
    }
}....

我有这个 AORule 的包装类,它使用 GPARS activeObject 来管理这样的DynamicRule rule引用状态,其中execute()方法调用 async activeObject 方法来触发对内部rule引用的操作

@Component
@Scope("prototype")
@ActiveObject
@Slf4j
@EqualsAndHashCode
class AORule implements org.easyrules.api.Rule {

    //setup delegate dynamicRule and make it a part of this ActiveObject
    //prototyped setter injection
    //@Autowired
    //@Scope ("prototype")
    //@Qualifier ("dynamicRule")
    @Delegate DynamicRule rule

    AORule (name, description=null) {
        log.debug "Create aorule.rule name/desc constructor called "
        rule = new DynamicRule (name, description ?: "Basic Active Object Rule")
    }

    AORule () {
        log.debug "Create aorule.rule default constructor called "
        rule = new DynamicRule ()
    }

    @Autowired (/*required=true*/)
    AORule (@Qualifier ("dynamicRule") DynamicRule dynrule) {
        log.debug "Create aorule.rule injected rule constructor called "
        rule = dynrule
    }
    ....
   void execute () {
        active_execute()
    }

    /**
     * Active method manages async action through object inside through hidden actor.
     * variable 'rule' is the variable we are protecting.  Runs either any dynmicExecution closure
     * where defined or just runs the standard class execute method
     *
     * @return void
     */
    @ActiveMethod
    void active_execute () {
        //rule.execute()

        log.debug "activeExec : rule dump looks like   " + rule.dump()

        def val = rule.dynamicExecution
        assert val == true

        log.debug "activeExec : ret value of rule.getDynamicExecution() was > " + val

        if (val != null) {
            log.debug "activeExec : running dynamicExecution closure, where rule closure was " + rule?.dynamicExecution.toString()
            rule.dynamicExecute()  //should call method that executes closure, where this is defined
        }
        else {
            log.debug "activeExec : running std Execution action  "
            rule.execute()

        }

    }

我一直在尝试编写一些测试来证明这对我自己有效并且它失败了。mockres我已经尝试对 dynamicRule 本身进行两个简单的测试,这很有效 - 我设置了期望并要求 Mock 调用闭包并测试该闭包对变量的副作用- 一切正常:

def "set execution closure using spock mock  but call stub directly  when doing an execute action " () {

    given:"setup of stub for testing "

    def mockres = ""

    def clos = {
        mockres = "did nothing";
        println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
    }

    //spock mock
    DynamicRule stub =  Mock  ()
    1*stub.dynamicExecute() >> {clos()}  // pretend this has been set


    when : "execution on stub directly  "

    stub.dynamicExecute()

    then : "test execute closure ran as expected "
    mockres == "did nothing"

}

在我的第二个测试中,我设置了 Mock 并将其设置在 aorule.rule 实例上并设置了对 mock 的期望,aorule.execute()调用调用activeExecute()active 方法的方法,该方法调用我的 mock

def "set execution closure using spock mock  but call aorule.execute()  when doing an execute action " () {

    given:"setup of stub for testing "

    def mockres = ""

    def clos = {
        mockres = "did nothing";
        println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
    }

    //spock mock
    DynamicRule stub =  Mock  ()
    1*stub.getDynamicExecution() >> { true }
    1*stub.dynamicExecute() >> {clos()}  // pretend this has been set

    println "test: save stub on aorule"
    aorule.rule = stub

    when : "call execute() on aorule.rule for stub   "

    //stub.dynamicExecute()
    //aorule.rule.dynamicExecute()  //works
    println "test: call aorule.execute"
    aorule.execute()   //think this must be getting a new prototype object which is why not getting called

    then : "test execute closure ran as expected "
    mockres == "did nothing"

}

这失败了 - 为什么没有在模拟上运行闭包,然后:断言测试失败。

我在这里包含了部分输出跟踪 - 你可以看到它aorule.execute()触发了 activeObject 方法,我可以看到日志跟踪activeExec : rule dump looks like - 但是在那之后它似乎都停止了,没有额外的跟踪输出(我期待看到价值val 例如),并且未调用存根闭包并且未设置 mockres - 测试失败

...
test: save stub on aorule
13:07:45.361 [main] DEBUG org.easyrules.spring.AORule - setting aorule.rule with > Mock for type 'DynamicRule' named 'stub'
test: call aorule.execute
13:07:45.367 [Actor Thread 1] DEBUG org.easyrules.spring.AORule - activeExec : rule dump looks like   <org.easyrules.spring.DynamicRule$$EnhancerByCGLIB$$9b33215e@a4770a4 CGLIB$BOUND=false CGLIB$CALLBACK_0=org.spockframework.mock.runtime.CglibMockInterceptorAdapter@4809f9c CGLIB$CALLBACK_1=net.sf.cglib.proxy.NoOp$1@bf1bd4 dynamicEvaluation=null dynamicExecution=null sync=null name=null description=null priority=0>
13:07:45.441 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@5c6648b0 testClass = AORuleSpecTest2, testInstance = org.easyrules.spring.AORuleSpecTest2@d41f816, testMethod = $spock_feature_0_1@AORuleSpecTest2, testException = Condition not satisfied:

mockres == "did nothing"
|       |
""      false
        11 differences (0% similarity)
        (-----------)
        (did nothing)
, mergedContextConfiguration = [MergedContextConfiguration@6f1de4c7 testClass = AORuleSpecTest2, locations = '{}', classes = '{class org.easyrules.spring.AORule, class org.easyrules.spring.DynamicRule}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].

Condition not satisfied:

我一直在尝试跟踪这一点,或者在调试器中观看无济于事。我的存根关闭未触发 - 测试失败。

我刚刚尝试再次在调试器中观看,当我越过这条线时

    def val = rule.dynamicExecution

调试器跳转到InternalActor.handleCurrentMessage()GPAR 中某处的错误处理程序。如果我将其更改为

    def val = rule.getDynamicExecution()  //try to get value via groovy auo method

我不明白这一点。也许我在做一些愚蠢的事情,但是我无法为我的代码编写测试来@ActiveMethod - activeExecute()使用 Mocks 测试代码(我试图通过手工制作的类等来做到这一点,并且无法让模拟测试工作。

如何正确纠正和运行测试?据我所知 - 当我在脚本(“实时”测试)中运行代码时,代码似乎做了我想做的事情,等等,但我无法进行单元测试来证明这一点

后记:这与 ActiveMethod 包装有关 - 不确定是什么

我在测试脚本中创建了两个虚拟包装器类,如下所示——一个不支持 ActiveObject,一个支持 ActiveObject——两者都调用dynamicExecute()嵌入规则的方法。AOWrappers 是@ActiveMethod

class WrapperRule {
    @Autowired   //property injection
    @Delegate DynamicRule rule

    WrapperRule () {

    }

    WrapperRule (DynamicRule irule) {
        rule = irule
        assert rule
    }

    void execute () {
        rule.dynamicExecute()
    }

}

@ActiveObject
@Slf4j
@EqualsAndHashCode
class AOWrapperRule {
    @Autowired   //property injection
    @Delegate DynamicRule rule

    AOWrapperRule () {

    }

    AOWrapperRule (DynamicRule irule) {
        rule = irule
        assert rule
    }

    @ActiveMethod
    void execute () {
        rule.dynamicExecute()
    }

}

同一个脚本文件中的两个测试看起来像这样

def "set execution closure using spock mock  on simple Wrapper rule  when doing an execute action " () {

    given:"setup of stub for testing "

    def mockres = ""

    def clos = {
        mockres = "did nothing";
        println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
    }

    WrapperRule wrule = new WrapperRule ()

    //spock mock
    DynamicRule stub =  Mock  ()
    1*stub.dynamicExecute() >> {clos()}  // pretend this has been set

    println "test: save stub on wrule"
    wrule.rule = stub

    when : "call execute() on wrule.rule for stub   "

    println "test: call wrule.execute"
    wrule.execute()   //think this must be getting a new prototype object which is why not getting called

    then : "test execute closure ran as expected "
    mockres == "did nothing"

}

def "set execution closure using spock mock  on AO Wrapper rule  when doing an execute action " () {

    given:"setup of stub for testing "

    def mockres = ""

    def clos = {
        mockres = "did nothing";
        println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
    }

    AOWrapperRule aowrule = new AOWrapperRule ()

    //spock mock
    DynamicRule stub =  Mock  ()
    1*stub.dynamicExecute() >> {clos()}  // pretend this has been set

    println "test: save stub on aowrapper"
    aowrule.rule = stub

    when : "call execute() on aowrule.rule for stub   "

    println "test: call aowrule.execute"
    aowrule.execute()   //think this must be getting a new prototype object which is why not getting called

    then : "test execute closure ran as expected "
    mockres == "did nothing"

}

当我运行测试时 - 第一个通过就好了,第二个失败并且我clos没有被调用。接下来我应该尝试什么?

澄清问题

我已经尝试并将其简化为单个 groovy 测试文件 - 正在测试类并且测试在同一个文件中,以便您可以希望看到发生了什么

package org.easyrules.spring

import groovy.mock.interceptor.StubFor
import groovy.transform.EqualsAndHashCode
import groovy.util.logging.Slf4j
import groovyx.gpars.activeobject.ActiveMethod
import groovyx.gpars.activeobject.ActiveObject
import org.junit.runner.RunWith
import org.softwood.RulesApplication
import org.springframework.beans.factory.annotation.Autowire
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration
import org.springframework.context.ApplicationContext
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import spock.lang.Specification
import spock.lang.Unroll
import spock.lang.*

/**
 * Created by William on 10/03/2016.
 */

class TestRule {
    Closure dynamicExecute = {println "default rule Execution "}

    def exec () {
        dynamicExecute()
    }
}


class TestWrapperRule {
    @Delegate TestRule rule

    TestWrapperRule () {
        rule = new TestRule()
    }

    void execute () {
        rule.exec()
    }

}

@ActiveObject
@Slf4j
@EqualsAndHashCode
class TestAOWrapperRule {
    @Delegate TestRule rule

    TestAOWrapperRule () {
        rule = new TestRule()
    }

    @ActiveMethod
    void execute () {
        rule.exec()
    }

}

class AORuleSpecAllInOneSpecTest extends Specification {

    def "test simple closure setting mockres value - basics " () {
        given:
        def mockres = ""

        def clos = {
            mockres = "did nothing";
            println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
        }

        when:
        clos()  //call closure

        then: "test mockres was set when closure called "
        mockres == "did nothing"
    }

    def "set execution closure using spock mock  on simple Wrapper rule  when doing an execute action " () {

        given:"setup of stub for testing "

        def mockres = ""

        def clos = {
            mockres = "did nothing";
            println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
        }

        TestWrapperRule wrule = new TestWrapperRule ()

        //spock mock
        TestRule stub =  Mock  ()
        //1*stub.exec() >> {clos()}  // pretend this has been set
        1*stub.getDynamicExecute() >> {clos()}  // pretend this has been set

        println "test: save stub on wrule"
        wrule.rule = stub

        when : "call execute() on wrule.rule for stub   "

        println "test: call wrule.execute"
        //wrule.exec()
        wrule.dynamicExecute

        then : "test execute closure ran as expected "
        mockres == "did nothing"

    }

    def "set execution closure using spock mock  on AO Wrapper rule  when doing an execute action " () {

        given:"setup of stub for testing "

        def mockres = ""

        def clos = {
            mockres = "did nothing";
            println "script: in stub closure, setting mockres to  " + mockres + " mockres dump > " + mockres.dump();
        }

        TestAOWrapperRule aowrule = new TestAOWrapperRule ()

        //spock mock
        TestRule stub =  Mock  ()
        stub.exec() >> {clos()}  // pretend this has been set

        println "test: save stub on aowrapper"
        aowrule.rule = stub

        when : "call execute() on aowrule.rule for stub   "

        println "test: call aowrule.execute"
        aowrule.execute()
        //aowrule.exec()  //if you then call the @delegate func without the activeMethod the test will work 

        then : "test execute closure ran as expected "
        mockres == "did nothing"

    }
}

需要注意的关键点是最后的测试。我在 Mock 上设置了期望运行输出闭包,这将更新mockres变量,我可以断言已在 then: 子句中设置。

当您调用@ActiveMethod execute()测试时,测试将像这样失败

...script: in stub closure, setting mockres to  did nothing mockres dump > <java.lang.String@c141192c value=did nothing hash=-1052698324>

Condition not satisfied:

mockres == "did nothing"
|       |
""      false
        11 differences (0% similarity)
        (-----------)
        (did nothing)

这表明闭包调用没有设置 mockres。

如果您取消注释后面的 aowrule.exec() 行 - 然后exec()直接调用委托调用 - 不使用 ActiveMethod 使用的隐藏参与者。当您运行下一行时,正确调用了闭包并设置了 mockres。

所以这个问题有一些事情要做,它试图通过隐藏的演员来测试模拟是否有效@ActiveMothod

我认为实际上,如果只是作为脚本运行(在代码中真正使用),代码正在做我期望的事情。但是,当调用 ActiveMethod 时,我似乎无法编写证明预期行为的测试。

我是否必须做一些聪明的事情来使用 Mocks 为 GPAR 之类的异步代码编写 spock 测试 - 或者这是应该工作但没有工作的东西。

4

0 回答 0