- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对没有 TestNG 的 Java 项目有以下要求,但我添加了 @Test
注释来运行该类。
1. Find the classes which are all annotated with `@controller` in the class path
2. Find the methods which are annotated with `@Requestmapping`
3. Infer all the method properties for each classes
4. Load Known details from Excel(Method name, HttpResponsecode, username, password)
5. Send HttpPost or HttpGet or HttpPUT
现在我想将上述功能从 1 到 4 转换为 @DataProvider
并调用 @Test
方法。我该怎么做?
示例代码是:
package com.hexgen.reflection.integration;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.hexgen.reflection.request.MethodInfoRO;
import com.hexgen.reflection.request.MethodParamsInfoRO;
import com.hexgen.reflection.support.HexgenControllerClassFinder;
import com.hexgen.reflection.support.HexgenWebAPITestConstants;
import com.hexgen.reflection.support.LoadMethodDetailsInfoFromExcel;
/**
*
* @author anthony
*
*/
public class HexgenWebAPITest {
/**
* This class finds the method which are not secured
* and makes sure that the method which are secured works properly
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void hexgenWebAPITest( ) {
int statusCode=0;
String[] requestMappingValues=null;
String[] parametersDefinedForMethod=null;
String strClassname="";
String strClassNameToFix="";
String requestingMethod="";
String uri="";
HttpClient client = new DefaultHttpClient();
List<MethodParamsInfoRO> tempParamsList = null;
List<String> notSecuredMethodsList = new ArrayList<String>();
Map<String,String> requestingMethodMap = new LinkedHashMap<String,String>();
Map<String,String> methodsMap = new LinkedHashMap<String, String>();
Map<String,List> paramsDetailsMap = new LinkedHashMap<String, List>();
Map<String,String> urlDetailsMap = new LinkedHashMap<String, String>();
Map<String,MethodInfoRO> knownGoodMap = new LinkedHashMap<String, MethodInfoRO>();
HexgenControllerClassFinder hexgenClassUtils = new HexgenControllerClassFinder();
HttpClientRequests httpRequest = new HttpClientRequests();
MethodParamsInfoRO methodParams ;
LoadMethodDetailsInfoFromExcel methodDetails = new LoadMethodDetailsInfoFromExcel();
Class cls;
try {
List controllerClassNames = hexgenClassUtils.findControllerClasses(HexgenWebAPITestConstants.BASE_PACKAGE);
Iterator<Class> className = controllerClassNames.iterator();
while(className.hasNext())
{
Class obj = className.next();
cls = Class.forName(obj.getName());
Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class); // gets the method which is maped with RequestMapping Annotation
if(requestMappingAnnotation !=null){ // requestMappingAnnotation if condition Starts
PreAuthorize preAuthorizeAnnotation = method.getAnnotation(PreAuthorize.class); // gets the method which is maped with PreAuthorize Annotation
if(preAuthorizeAnnotation == null){ // preAuthorizeAnnotation if condition Starts
notSecuredMethodsList.add("Class : "+obj.getName()+" Method : "+method.getName());
} // preAuthorizeAnnotation if condition Ends
requestMappingValues = requestMappingAnnotation.value(); // to get the url value
RequestMethod[] requestMethods = requestMappingAnnotation.method(); // to get the request method type
requestingMethod = requestMethods[0].name();
methodsMap.put(requestMappingValues[0],method.getName());
//Following lines to get the request url and the requesting method type
urlDetailsMap.put(method.getName(), requestMappingValues[0]);
requestingMethodMap.put(method.getName(), requestingMethod);
Class[] parameterTypes = method.getParameterTypes();
LocalVariableTableParameterNameDiscoverer lcl = new LocalVariableTableParameterNameDiscoverer();
parametersDefinedForMethod = lcl.getParameterNames(method);
tempParamsList = new ArrayList();
for (int i=0;i<parameterTypes.length;i++) { // check the parameter type and put them in to a ArrayList
methodParams = new MethodParamsInfoRO();
Class parameterType=parameterTypes[i];
strClassNameToFix = parameterType.getName();
strClassname =strClassNameToFix.replaceAll(HexgenWebAPITestConstants.PATTERN_TO_REMOVE,HexgenWebAPITestConstants.PATH_VARIABLE_TO_REPLACE).replaceAll(HexgenWebAPITestConstants.PATTERN_TO_REMOVE_SEMICOLON,HexgenWebAPITestConstants.PATH_VARIABLE_TO_REPLACE);
methodParams.setDataType(strClassname);
methodParams.setVariableDefined(parametersDefinedForMethod[i]);
if(parameterType.isArray()){
methodParams.setArray(true);
}
if(parameterType.isPrimitive()){
methodParams.setPrimitive(true);
}
//FIXME find some better way to address this problem
if (strClassname.equals("java.math.BigDecimal")|| strClassname.equals("java.lang.String")|| strClassname.equals("boolean")) {
methodParams.setPrimitive(true);
}
tempParamsList.add(methodParams);
}
paramsDetailsMap.put(method.getName(),tempParamsList);
//paramsList.add(tempParamsList);
}//requestMappingAnnotation if condition Ends
}
}
/** HTTPResponeCodes
* =================
* 1. 200 Response Successful
*
* 2. 400 Bad Request(The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.)
*
* 3. 403 Forbidden
*
* 4. 405 Method Not Allowed (The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.)
*
* 5. 500 Internal Server Error(The server encountered an unexpected condition which prevented it from fulfilling the request.)
*
*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我使用 apache-httpclient 4.0 进行服务器通信。
最佳答案
您可以检查以下内容,希望这对您有所帮助。祝你好运。
@Test(dataProvider = "HexgenControllersData")
public void hexgenControllersTest(KnownGoodInfo knownGoodInfoRO, Object[] methodInfoObject) throws Exception {
int httpResponseStatus=0;
String requestURL = "";
HttpClient authenticationObject = null;
MethodProperties methodPropertiesRO = null;
HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
methodPropertiesRO = (MethodProperties) methodInfoObject[0];
//Attempts to login to hexgen application
authenticationObject = httpRequestHandler.loginToHexgen(knownGoodInfoRO.getUser(), knownGoodInfoRO.getPassword());
requestURL = HexgenControllersTestConstants.DEFAULT_URL + methodPropertiesRO.getUrl();
//Attempts to send url request and gets the http response code
httpResponseStatus = httpRequestHandler.handleHTTPRequest(authenticationObject, requestURL,methodPropertiesRO.getRequestingMethod(),(List) methodInfoObject[1]);
Assert.assertEquals(knownGoodInfoRO.getHttpResponse(), httpResponseStatus);
}
@DataProvider(name = "HexgenControllersData")
public static Object[][] dataProviderForSecurityinference() {
String[] requestMappingValues = null;
String[] parametersDefinedForMethod = null;
String strClassname = "";
String strClassNameToFix = "";
String requestingMethod = "";
List<MethodParamsInfo> tempParamsList = null;
List<String> notSecuredMethodsList = null;
Map<String, List> methodParametersMap = new LinkedHashMap<String, List>();
Map<String, MethodProperties> methodPropertiesMap = new LinkedHashMap<String, MethodProperties>();
Map<String, KnownGoodInfo> knownGoodMap = null;
MethodParamsInfo methodParams = null;
MethodProperties methodPropertiesRO = null;
DataProviderForHexgenControllers dataProviderForHexgenControllers = null;
try {
dataProviderForHexgenControllers = new DataProviderForHexgenControllers();
Class classInstance;
List controllerClassNames = dataProviderForHexgenControllers.findControllerClasses(HexgenControllersTestConstants.BASE_PACKAGE);
Iterator<Class> classNames = controllerClassNames.iterator();
notSecuredMethodsList = new ArrayList<String>();
while (classNames.hasNext()) {
Class className = classNames.next();
classInstance = Class.forName(className.getName());
Method[] methods = classInstance.getDeclaredMethods();
for (Method method : methods) {
// gets the method which is maped with RequestMapping Annotation
RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class);
// requestMappingAnnotation if condition Starts
if (requestMappingAnnotation != null) {
PreAuthorize preAuthorizeAnnotation = method.getAnnotation(PreAuthorize.class);
// record the method name if it is not annotated with preAuthorize
if (preAuthorizeAnnotation == null) {
notSecuredMethodsList.add("Class : "+className.getName() + " Method : " + method.getName());
}
// to get the url value
requestMappingValues = requestMappingAnnotation.value();
// to get the request method type
RequestMethod[] requestMethodWithURL = requestMappingAnnotation .method();
requestingMethod = requestMethodWithURL[0].name();
// Attempts to get the request url and the requesting method type
methodPropertiesRO = new MethodProperties();
methodPropertiesRO.setRequestingMethod(requestingMethod);
methodPropertiesRO.setUrl(requestMappingValues[0]);
methodPropertiesMap.put(method.getName(),methodPropertiesRO);
Class[] parameterTypes = method.getParameterTypes();
LocalVariableTableParameterNameDiscoverer localVariableDefinedDiscover = new LocalVariableTableParameterNameDiscoverer();
parametersDefinedForMethod = localVariableDefinedDiscover
.getParameterNames(method);
tempParamsList = new ArrayList();
// check the parameter type and put them in to a
// ArrayList
for (int i = 0; i < parameterTypes.length; i++) {
methodParams = new MethodParamsInfo();
Class parameterType = parameterTypes[i];
strClassNameToFix = parameterType.getName();
strClassname = strClassNameToFix .replaceAll( HexgenControllersTestConstants.PATTERN_TO_REMOVE,HexgenControllersTestConstants.PATTERN_TO_REPLACE)
.replaceAll( HexgenControllersTestConstants.PATTERN_TO_REMOVE_SEMICOLON, HexgenControllersTestConstants.PATTERN_TO_REPLACE);
methodParams.setDataType(strClassname);
methodParams.setVariableDefined(parametersDefinedForMethod[i]);
if (parameterType.isArray()) {
methodParams.setArray(true);
}
if (parameterType.isPrimitive()) {
methodParams.setPrimitive(true);
}
// FIXME find some better way to address this problem
if (strClassname .equals(HexgenControllersTestConstants.BIGDECIMAL)
|| strClassname .equals(HexgenControllersTestConstants.STRING)
|| strClassname .equals(HexgenControllersTestConstants.BOOLEAN))
{
methodParams.setPrimitive(true);
}
tempParamsList.add(methodParams);
}
methodParametersMap.put(method.getName(),tempParamsList);
}// requestMappingAnnotation if condition Ends
}
}
dataProviderForHexgenControllers = new DataProviderForHexgenControllers();
knownGoodMap = new LinkedHashMap<String, KnownGoodInfo>();
knownGoodMap = dataProviderForHexgenControllers.getKnownGoodMap(HexgenControllersTestConstants.KNOWN_GOOD_FILE_PATH);
} catch (Exception dataProviderForSecurityinferenceException) {
dataProviderForSecurityinferenceException.printStackTrace();
}
List<Object[]> hexgenSecurityInferenceData = new ArrayList<Object[]>();
for (String methodName:knownGoodMap.keySet()) {
hexgenSecurityInferenceData.add(new Object[] {
knownGoodMap.get(methodName),
new Object[] {
methodPropertiesMap.get(methodName),
methodParametersMap.get(methodName)
}
});
}
Object[][] securityInferenceData = hexgenSecurityInferenceData.toArray(new Object[0][]);
return securityInferenceData;
}
让我知道结果,如果这是您正在寻找的,请尽量不要忘记接受这个答案。
关于java - TestNG @Dataprovider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536221/
我想多次运行一个测试用例。在testng.xml中可以配置吗?如果在测试方法中添加循环,则每次运行的结果将不会受到testng报告的影响。 最佳答案 您不能通过xml来执行此操作,但是可以在@Test
我在 TestNG 中尝试了一些使用硬断言和软断言的示例。虽然软断言按预期工作,但我遇到了硬断言的问题。 根据我从互联网上读到的信息-如果硬断言失败,它不会执行其他测试。 由于 ffPageEleme
我能够在 Eclipse 中完美地运行 testng。但是,我想使用命令行(Win 8)运行它,如不同论坛上所述。以下是我尝试处理错误的不同方法 - 1. java -cp "D:\testng\te
假设我有一个可以并行或串行执行的套件。但是,这样做的决定要留给运行时。启动此套件的常见方法如下: TestNG runner = new TestNG(); if (runInParallel())
如何获得执行TESTNG的方法所花费的时间? sample 测试: @Test(threadPoolSize = 100, invocationCount = 100) public void tes
我发现有一个选项可以通过surefire插件将参数设置为testng xml,然后可以从命令行发送参数。 [...] org.apache.maven.plug
我正在尝试使用这样的命令行运行 testng 测试: C:\Documents and Settings\Administrateur\Bureau\automatic tests testNG>ja
我正在尝试从我的套件文件中删除 testng 参数,因为它们在多个套件中都需要。例如,我有 2 个测试套件,upgrades.xml 和 features.xml。我创建了第三个文件,paramete
目标:并行独立运行 2 个类,其中每个测试将方法名称存储到一个变量中,该变量稍后可以在测试中访问。 问题:当测试并行运行时,它们开始在它们之间共享数据,从而破坏测试。 如果您看到控制台输出这是错误的:
好的,请引用 TestNG doc我可以运行测试 依次 (默认在测试套件中)或在 平行使用 . 现在这是我的 TestNG 配置
我正在尝试从命令行运行TestNG,但这给了我错误。 有人可以告诉我我要去哪里错吗? java -cp C:/TestNG目录/testng-6.2.jar;C:\project目录\src\com\
情况和问题 我有几个测试类,每个类都有几个测试方法。所有测试在后台使用相同的测试数据库。每个测试类初始化其数据库内容,然后在几个测试方法中测试内容。 当我单独运行每个测试时,它们都通过了。但是当我同时
如何让我的 TestNG 报告显示报告中控制台输出的链接?我以前见过 TestNG 这样做,但我现在正在做的一个项目没有显示任何输出,而且我在任何地方都找不到任何说明如何打开它的信息。我尝试在 tes
如果断言失败,如何在 TestNG 中继续执行测试?如何在 TestNG 的 HTML 报告中报告失败? 当我运行以下代码时,执行了断言之后的行,但在报告中未列出断言失败: @Test public
如果断言失败,如何在 TestNG 中继续执行测试?如何在 TestNG 的 HTML 报告中报告失败? 当我运行以下代码时,执行了断言之后的行,但在报告中未列出断言失败: @Test public
我在每个 wiki 使用 TestNG + ReportNG instructions在 gradle 中(我固定在食谱上,因为默认示例对我不起作用)。 我想以某种方式在 TestNG 中捕获控制台输
如何使用 TestNG 自动化功能测试,跨越多个 Java 进程? 我对尝试使用 TestNG 而不是 JUnit 产生了兴趣,因为它声称不仅仅是为单元测试而设计的,但我还没有找到具体的例子来说明如何
如何在测试用例的运行时获取当前正在运行的套件名称?我正在使用下面显示的代码来获取当前套件名称。 监听类: public class SuiteListener implements ISuiteLis
我正在使用 Selenium Webdriver 和 Java 设计一个用于测试的定制自动化框架。 现在出于报告的目的,我正在尝试将 TestNG 框架与我的项目集成。 现在我有一个基于 GUI 的界
出于某种原因,我必须使用旧的 TestNG 库,它没有 "getCurrentXmlTest()).getAllParameters()" API 我应该如何使用testng-5.4-jdk15.ja
我是一名优秀的程序员,十分优秀!