junitsampler.java

来自「测试工具」· Java 代码 · 共 549 行 · 第 1/2 页

JAVA
549
字号

    /**
     * set the setup/teardown option
     * @param setup
     */
    public void setDoNotSetUpTearDown(boolean setup){
        setProperty(DOSETUP,String.valueOf(setup));
    }

    /**
     * If append error is not set, by default it is set to false,
     * which means users have to explicitly set the sampler to
     * append the assert errors. Because of how junit works, there
     * should only be one error
     */
    public boolean getAppendError() {
        return getPropertyAsBoolean(APPEND_ERROR,false);
    }
    
    public void setAppendError(boolean error) {
        setProperty(APPEND_ERROR,String.valueOf(error));
    }

    /**
     * If append exception is not set, by default it is set to false.
     * Users have to explicitly set it to true to see the exceptions
     * in the result tree.
     */
    public boolean getAppendException() {
        return getPropertyAsBoolean(APPEND_EXCEPTION,false);
    }
    
    public void setAppendException(boolean exc) {
        setProperty(APPEND_EXCEPTION,String.valueOf(exc));
    }
    
    /* (non-Javadoc)
	 * @see org.apache.jmeter.samplers.Sampler#sample(org.apache.jmeter.samplers.Entry)
	 */
	public SampleResult sample(Entry entry) {
		SampleResult sresult = new SampleResult();
        String rlabel = null;
        if (getConstructorString().length() > 0) {
            rlabel = getConstructorString();
        } else {
            rlabel = JUnitSampler.class.getName();
        }
        sresult.setSampleLabel(getName());// Bug 41522 - don't use rlabel here
        sresult.setSamplerData(getClassname() + "." + getMethod());   
        // check to see if the test class is null. if it is, we create
        // a new instance. this should only happen at the start of a
        // test run
        if (this.TEST_INSTANCE == null) {
            this.TEST_INSTANCE = (TestCase)getClassInstance(getClassname(),rlabel);
        }
        if (this.TEST_INSTANCE != null){
            initMethodObjects(this.TEST_INSTANCE);
            // create a new TestResult
            TestResult tr = new TestResult();
            this.TEST_INSTANCE.setName(getMethod());
            try {
                
                if (!getDoNotSetUpTearDown() && SETUP_METHOD != null){
                    try {
                        SETUP_METHOD.invoke(this.TEST_INSTANCE,new Class[0]);
                    } catch (InvocationTargetException e) {
                        tr.addFailure(this.TEST_INSTANCE, 
                                new AssertionFailedError(e.getMessage()));
                    } catch (IllegalAccessException e) {
                        tr.addFailure(this.TEST_INSTANCE, 
                                new AssertionFailedError(e.getMessage()));
                    } catch (IllegalArgumentException e) {
                        tr.addFailure(this.TEST_INSTANCE, 
                                new AssertionFailedError(e.getMessage()));
                    }
                }
                final Method m = getMethod(this.TEST_INSTANCE,getMethod());
                final TestCase theClazz = this.TEST_INSTANCE;
                tr.startTest(this.TEST_INSTANCE);
                sresult.sampleStart();
                // Do not use TestCase.run(TestResult) method, since it will
                // call setUp and tearDown. Doing that will result in calling
                // the setUp and tearDown method twice and the elapsed time
                // will include setup and teardown.
                Protectable p = new Protectable() {
                    public void protect() throws Throwable {
                        m.invoke(theClazz,new Class[0]);
                    }
                };
                tr.runProtected(theClazz, p);
                tr.endTest(this.TEST_INSTANCE);
                sresult.sampleEnd();
                
                if (!getDoNotSetUpTearDown() && TDOWN_METHOD != null){
                    TDOWN_METHOD.invoke(TEST_INSTANCE,new Class[0]);
                }
            } catch (InvocationTargetException e) {
                // log.warn(e.getMessage());
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            } catch (IllegalAccessException e) {
                // log.warn(e.getMessage());
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            } catch (ComparisonFailure e) {
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            } catch (IllegalArgumentException e) {
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            } catch (Exception e) {
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            } catch (Throwable e) {
                sresult.setResponseCode(getErrorCode());
                sresult.setResponseMessage(getError());
                sresult.setResponseData(e.getMessage().getBytes());
                sresult.setSuccessful(false);
            }
            if ( !tr.wasSuccessful() ){
                sresult.setSuccessful(false);
                StringBuffer buf = new StringBuffer();
                buf.append( getFailure() );
                Enumeration en = tr.errors();
                while (en.hasMoreElements()){
                    Object item = en.nextElement();
                    if (getAppendError() && item instanceof TestFailure) {
                        buf.append( "Trace -- ");
                        buf.append( ((TestFailure)item).trace() );
                        buf.append( "Failure -- ");
                        buf.append( ((TestFailure)item).toString() );
                    } else if (getAppendException() && item instanceof Throwable) {
                        buf.append( ((Throwable)item).getMessage() );
                    }
                }
                sresult.setResponseMessage(buf.toString());
                sresult.setRequestHeaders(buf.toString());
                sresult.setResponseCode(getFailureCode());
            } else {
                // this means there's no failures
                sresult.setSuccessful(true);
                sresult.setResponseMessage(getSuccess());
                sresult.setResponseCode(getSuccessCode());
                sresult.setResponseData("Not Applicable".getBytes());
            }
        } else {
            // we should log a warning, but allow the test to keep running
            sresult.setSuccessful(false);
            // this should be externalized to the properties
            sresult.setResponseMessage("failed to create an instance of the class");
        }
        sresult.setBytes(0);
        sresult.setContentType("text");
        sresult.setDataType("Not Applicable");
        sresult.setRequestHeaders("Not Applicable");
		return sresult;
	}

    /**
     * If the method is not able to create a new instance of the
     * class, it returns null and logs all the exceptions at
     * warning level.
     */
    public static Object getClassInstance(String className, String label){
        Object testclass = null;
        if (className != null){
            Constructor con = null;
            Constructor strCon = null;
            Class theclazz = null;
            Object[] strParams = null;
            Object[] params = null;
            try
            {
                theclazz = 
                    Thread.currentThread().getContextClassLoader().loadClass(className.trim());
            } catch (ClassNotFoundException e) {
                log.warn("ClassNotFoundException:: " + e.getMessage());
            }
            if (theclazz != null) {
                // first we see if the class declares a string
                // constructor. if it is doesn't we look for
                // empty constructor.
                try {
                    strCon = theclazz.getDeclaredConstructor(
                            new Class[] {String.class});
                    // we have to check and make sure the constructor is
                    // accessible. if we didn't it would throw an exception
                    // and cause a NPE.
                    if (label == null || label.length() == 0) {
                        label = className;
                    }
                    if (strCon.getModifiers() == Modifier.PUBLIC) {
                        strParams = new Object[]{label};
                    } else {
                        strCon = null;
                    }
                } catch (NoSuchMethodException e) {
                    log.info("String constructor:: " + e.getMessage());
                }
                if (con == null ){
                    try {
                        con = theclazz.getDeclaredConstructor(new Class[0]);
                        if (con != null){
                            params = new Object[]{};
                        }
                    } catch (NoSuchMethodException e) {
                        log.info("Empty constructor:: " + e.getMessage());
                    }
                }
                try {
                    // if the string constructor is not null, we use it.
                    // if the string constructor is null, we use the empty
                    // constructor to get a new instance
                    if (strCon != null) {
                        testclass = strCon.newInstance(strParams);
                    } else if (con != null){
                        testclass = con.newInstance(params);
                    }
                } catch (InvocationTargetException e) {
                    log.warn(e.getMessage());
                } catch (InstantiationException e) {
                    log.info(e.getMessage());
                } catch (IllegalAccessException e) {
                    log.info(e.getMessage());
                }
            }
        }
        return testclass;
    }
    
    /**
     * 
     * @param clazz
     * @param method
     * @return the method or null if an error occurred
     */
    public Method getMethod(Object clazz, String method){
        if (clazz != null && method != null){
            // log.info("class " + clazz.getClass().getName() +
            //        " method name is " + method);
            try {
                return clazz.getClass().getMethod(method,new Class[0]);
            } catch (NoSuchMethodException e) {
                log.warn(e.getMessage());
            }
        }
        return null;
    }
    
    public Method getRunTestMethod(Object clazz){
        if (clazz != null){
            // log.info("class " + clazz.getClass().getName() +
            //        " method name is " + RUNTEST);
            try {
                Class[] param = {TestResult.class};
                return clazz.getClass().getMethod(RUNTEST,param);
            } catch (NoSuchMethodException e) {
                log.warn(e.getMessage());
            }
        }
        return null;
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?