2013-05-14 5 views
1

У меня есть следующие требования для моего проекта Java без TestNG, но я добавил @Test Аннотацию для запуска класса.TestNG @Dataprovider

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 для сервера связи.

ответ

3

Вы можете проверить следующее, надеяться, что это сработает и поможет вам. Удачи.

@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; 
    } 

и дайте мне знать результаты и постарайтесь не забыть принять этот ответ, если это то, что вы ищете.

+1

Hi @Antony Я выполнил этот вопрос с тем же подходом, который вы предоставили. Спасибо за сообщение и +1 –

Смежные вопросы