代码之家  ›  专栏  ›  技术社区  ›  Ramesh Daddagol

AspectJ-捕捉所有用@FindBy注释的WebElement的切入点

  •  1
  • Ramesh Daddagol  · 技术社区  · 7 年前

    我的测试框架使用selenium的PageFactory和Lambok。我想编写一个方面来捕获测试流在运行时遇到的所有web元素。

    典型页面如下所示:

    @Slf4j
    public class MyCustomPage {
    
        @Inject
        private IWebDriverSet driverSet;
    
        @Getter
        @FindBy(id = PAGE_ROOT)
        private WebElement root;
    
        @FindAll({
                @FindBy(css = FOOT_BAR),
                @FindBy(css = FOOT_BAR_B)
        })
        private WebElement navBar;
    }
    

    @FindBy确定测试处理的webelement。其中有50页。

    当使用PageFactory实例化页面时,将实例化webElement字段(使用与@FindBy中的值对应的webElement实例进行分配)。

    我想在实例化这些webElements后立即捕获这些用@FindBy/@FindAll注释的webElements。 我不想为每个页面类编写单独的切入点。 怎么做?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Mihail    7 年前

    由于WebElement的值是通过反射指定的,所以不能用set()切入点指示符截取该值。但你可以追踪所有呼叫 java.lang.reflect.Field.set

        @After("call(* java.lang.reflect.Field.set(..)) && args(obj, value) && target(target)")
        public void webelementInit(JoinPoint jp, Object obj, Object value, Field target) {
            //obj - instance of a class (page object) that declares current field
            //value - new field value (instantiated WebElement)
            //field - current field
            //you can filter calls to the fields you need by matching target.getDeclaringClass().getCanonicalName() with page object's package
            //for example:
            //if(target.getDeclaringClass().getCanonicalName().contains("com.example.pageobjects")) {
                //do stuff
            //}
        }
    

    在这种情况下,您需要在pom的dependencies部分中定义rt.jar。xml

    <dependencies>
            <dependency>
                <groupId>java</groupId>
                <artifactId>jre-runtime</artifactId>
                <version>1.8</version>
                <scope>system</scope>
                <systemPath>${java.home}/lib/rt.jar</systemPath>
            </dependency>
    ...
    </dependencies>
    

    在aspectj maven插件的weaveDependencies部分

    <weaveDependencies>
        <weaveDependency>
            <groupId>java</groupId>
            <artifactId>jre-runtime</artifactId>
        </weaveDependency>
    ...
    </weaveDependencies>