- 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/
这个问题已经有答案了: LIMIT is not working in ActiveDataProvider (2 个回答) 已关闭 7 年前。 偏移不起作用 - 正确吗?分页不起作用。 $query
我有一个简单的 PostControllerTest 类: client = static::createClient(); } public function idProvider(
有没有办法根据特定条件从数据提供者获取数据?类似的东西.. @Test(dataProvider = "Data-Provider-Function" class="Randomclass.class
我对没有 TestNG 的 Java 项目有以下要求,但我添加了 @Test 注释来运行该类。 1. Find the classes which are all annotated with `@c
如何使用存在于不同类中的@DataProvider? 我创建了一个不同的包,并在每个测试用例旁边定义了数据提供者。请分享我如何在不同的类里面使用它。 最佳答案 您可以使用@Test 的dataProv
我的@DataProvider看起来像这样: @DataProvider(name = "data") public Object[][] data() throws Exceptio
我有一个 Excel 电子表格,其中存储了所有测试信用卡。这些信用卡有不同的类型。其中一些是 VISA,其他是 MasterCard、Amex 等... 我有一个测试用例,其中我有时想使用 VISA
我已阅读有关该主题的文档,并且我的代码符合数据提供程序实现的所有要求。首先,here's the full code of the test以防万一。 这是实现数据提供者的功能: /** * Tes
我正在使用一个数组来填充一个 DataProvider,我正在使用它来填充一个列表组件。像这样: var myDataProvider = new DataProvider(this.myArray)
我有一个 PHPUnit 测试,它使用 @dataProvider .数据提供者检查文件系统中的某些文件。 但是,我在不同的环境中使用此测试,这意味着可能会发生文件不存在的情况。这意味着 dataPr
我想将网格中的一些数据延迟加载到我的 Vaadin View 中。网格行有时非常大,所以我想限制一次加载的行数,假设为 2。 我尝试使用 DataProvider.fromCallbacks() 来做
我如何计算 $dataProvider 检索的数据?我尝试过使用此代码, $dataProvider = new CActiveDataProvider('Model');
我有一个包含完整测试数据的 TestNG Dataprovider。我正在解析 Excel 工作表,因此 dataprovider 有例如。 15个测试数据列表。 我不想使用所有 15 个测试数据集运
这个问题已经有答案了: What causes a java.lang.StackOverflowError (13 个回答) 已关闭 4 年前。 我正在使用 Excel 工作表,因为我正在使用数据提
我需要在来自 DataProvider 的每个数据之前运行一些测试。 例如,在下面的示例类中,我需要运行 someStart 测试 4 次(在每个数据之前),如何执行此操作? public class
我有一组测试总共需要很长时间才能执行。我想通过将所有数据提供者更改为仅返回一组参数来缩短我的一些测试运行。 我已经通读了 TestNG 文档和 javadoc,但似乎没有像 IDataProvider
首先,我正在构建一个基于 Selenium 和 Java 的自动化库。我正在构建一种参数化传递到测试方法的数据的方法。我正在使用 TestNG。 现在我有两个示例测试方法,它们采用不同的数据模型作为参
您好,我正在使用 TestNG 在 Eclipse indigo 上进行测试。我已经设置了 DataProvider,奇怪的是控件正在跳过 DataProvider。它执行@BeforeClass和@
我有一个 DataProvider 可以读取如下所示的 CSV 文件 john|26|mba claire|33|bbl knight|29|mpa 现在我有三个类,每个类有一个@Test 类名是 N
我想在类中与数据提供程序并行运行测试方法。我需要一个数据提供程序,每次在新的测试方法开始为给定的测试运行生成部分动态数据之前都会调用该数据提供程序。让我用伪代码解释一下: @DataProvider(
我是一名优秀的程序员,十分优秀!