I am trying to fetch the resultsetmeta data using Spring jdbc template. It works fine if there is atleast one row returned.
The problem arises when there is no rows returned i.e. an empty resultSet.
I have tried a lot and still stuck up with the same. If there is any solution to this, please help me with this.
Also, I found ResultSetWrappingSqlRowSetMetaData class in spring. Is this of some use in my context?
Thanks for the help.
Finally I found the answer to my question. Below is the code:
template.query(builder.toString(),new ResultSetExtractor<Integer>() {
#Override
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1 ; i <= columnCount ; i++){
SQLColumn column = new SQLColumn();
column.setName(rsmd.getColumnName(i));
column.setAutoIncrement(rsmd.isAutoIncrement(i));
column.setType(rsmd.getColumnTypeName(i));
column.setTypeCode(rsmd.getColumnType(i));
column.setTableName(sqlTable.getName().toUpperCase());
columns.add(column);
}
return columnCount;
}
});
For a detailed explanation you can visit here
You can also use JdbcUtils
#SuppressWarnings("unchecked")
public static List<TableColumnTypeMap> getTableColumns(DataSource dataSource,
String tableName) {
try {
return (List<TableColumnTypeMap>) JdbcUtils.extractDatabaseMetaData(dataSource,
new DatabaseMetaDataCallback() {
#Override
public Object processMetaData(DatabaseMetaData dbmd)
throws SQLException, MetaDataAccessException {
ResultSet rs = dbmd
.getColumns("", "%", tableName + "%", null);
List<TableColumnTypeMap> list = new ArrayList();
while (rs.next()) {
String tableCat = rs.getString("TABLE_CAT");
String tableSchem = rs.getString("TABLE_SCHEM");
String tableName = rs.getString("TABLE_NAME");
String columnName = rs.getString("COLUMN_NAME");
String typeName = rs.getString("TYPE_NAME");
String columnSize = rs.getString("COLUMN_SIZE");
String nullable = rs.getString("NULLABLE");
String remarks = rs.getString("REMARKS");
int dataType = rs.getInt("DATA_TYPE");
System.out.println(tableName);
TableColumnTypeMap tableColumnTypeMap = new TableColumnTypeMap()
.setColumnName(columnName)
.setColumnType(typeName)
.setJavaClassName(getColumnCLassName(dataType))
.setRemarks(remarks);
list.add(tableColumnTypeMap);
}
return list;
}
});
} catch (MetaDataAccessException ex) {
throw new RuntimeException("get table list failed", ex);
}
}
for java class map:
private static String getColumnCLassName(int sqlType) {
String className = String.class.getName();
switch (sqlType) {
case Types.NUMERIC:
case Types.DECIMAL:
className = java.math.BigDecimal.class.getName();
break;
case Types.BIT:
className = java.lang.Boolean.class.getName();
break;
case Types.TINYINT:
className = java.lang.Byte.class.getName();
break;
case Types.SMALLINT:
className = java.lang.Short.class.getName();
break;
case Types.INTEGER:
className = java.lang.Integer.class.getName();
break;
case Types.BIGINT:
className = java.lang.Long.class.getName();
break;
case Types.REAL:
className = java.lang.Float.class.getName();
break;
case Types.FLOAT:
case Types.DOUBLE:
className = java.lang.Double.class.getName();
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
className = "byte[]";
break;
case Types.DATE:
className = java.sql.Date.class.getName();
break;
case Types.TIME:
className = java.sql.Time.class.getName();
break;
case Types.TIMESTAMP:
className = java.sql.Timestamp.class.getName();
break;
case Types.BLOB:
className = java.sql.Blob.class.getName();
break;
case Types.CLOB:
className = java.sql.Clob.class.getName();
break;
default:
break;
}
return className;
}
for result class
/**
* #author ryan
* #date 19-7-15 下午6:05
*/
#Data
#Accessors(chain = true)
public class TableColumnTypeMap {
private String columnName;
private String columnType;
private String javaClassName;
private String remarks;
}
Related
I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....
(The surface area of the ByteBuddy API is overwhelmingly enormous, which is why I'm asking the question.)
I'm aware that I can take a TypeDescription.Generic and determine its "sort" and proceed rather laboriously "by hand" from there, but often times I've found there is a method buried somewhere that will do this sort of tedious work for me.
EDIT: a commenter asked for the "tedious" recipe. Here it is (stand back; please note the various implementations of various Types are more or less what you'd expect them to be):
public static final Type toType(final TypeDefinition type) throws ReflectiveOperationException {
final Type returnValue;
if (type == null) {
returnValue = null;
} else {
final TypeDescription.Generic genericType = type.asGenericType();
switch (type.getSort()) {
case GENERIC_ARRAY:
returnValue = new DefaultGenericArrayType(toType(type.getComponentType()));
break;
case NON_GENERIC:
returnValue = Class.forName(type.getTypeName(), false, Thread.currentThread().getContextClassLoader());
break;
case PARAMETERIZED:
final TypeDefinition ownerType = genericType.getOwnerType();
final TypeDefinition rawType = type.asErasure();
final List<? extends TypeDefinition> actualTypeArguments = genericType.getTypeArguments();
if (actualTypeArguments == null || actualTypeArguments.isEmpty()) {
returnValue = new DefaultParameterizedType(toType(ownerType), toType(rawType));
} else {
final Type[] actualJavaTypeArguments = new Type[actualTypeArguments.size()];
for (int i = 0; i < actualTypeArguments.size(); i++) {
actualJavaTypeArguments[i] = toType(actualTypeArguments.get(i));
}
returnValue = new DefaultParameterizedType(toType(ownerType), toType(rawType), actualJavaTypeArguments);
}
break;
case VARIABLE:
final TypeVariableSource typeVariableSource = genericType.getTypeVariableSource();
final GenericDeclaration gd;
if (typeVariableSource instanceof TypeDefinition typeDefinition) {
gd = Class.forName(typeDefinition.asErasure().getTypeName(), false, Thread.currentThread().getContextClassLoader());
} else if (typeVariableSource instanceof MethodDescription.InDefinedShape methodDescription) {
// Reflection time
final String name = methodDescription.getName();
final Class<?> cls = Class.forName(methodDescription.getDeclaringType().asErasure().getTypeName(), false, Thread.currentThread().getContextClassLoader());
final List<? extends TypeDefinition> parameterTypes = methodDescription.getParameters().asTypeList();
final Class<?>[] parameterClasses = new Class<?>[parameterTypes.size()];
for (int i = 0; i < parameterTypes.size(); i++) {
parameterClasses[i] = Class.forName(parameterTypes.get(i).asErasure().getName(), false, Thread.currentThread().getContextClassLoader());
}
if (MethodDescription.CONSTRUCTOR_INTERNAL_NAME.equals(name)) {
assert TypeDescription.VOID.equals(methodDescription.getReturnType());
gd = cls.getDeclaredConstructor(parameterClasses);
} else {
assert !MethodDescription.TYPE_INITIALIZER_INTERNAL_NAME.equals(name);
gd = cls.getDeclaredMethod(name, parameterClasses);
}
} else {
throw new IllegalArgumentException("Unexpected type variable source: " + typeVariableSource);
}
final TypeVariable<?>[] typeVariables = gd.getTypeParameters();
TypeVariable<?> temp = null;
for (final TypeVariable<?> typeVariable : typeVariables) {
if (typeVariable.getName().equals(genericType.getSymbol())) {
temp = typeVariable;
break;
}
}
assert temp != null;
returnValue = temp;
break;
case VARIABLE_SYMBOLIC:
throw new IllegalArgumentException("Unexpected type: " + type);
case WILDCARD:
final List<? extends TypeDefinition> upperBounds = genericType.getUpperBounds();
final List<? extends TypeDefinition> lowerBounds = genericType.getLowerBounds();
if (lowerBounds == null || lowerBounds.isEmpty()) {
if (upperBounds == null || upperBounds.isEmpty() || (upperBounds.size() == 1 && TypeDescription.Generic.OBJECT.equals(upperBounds.get(0)))) {
returnValue = UnboundedWildcardType.INSTANCE;
} else {
// Upper bounded.
final Type[] upperJavaBounds = new Type[upperBounds.size()];
for (int i = 0; i < upperBounds.size(); i++) {
upperJavaBounds[i] = toType(upperBounds.get(i)); // XXX recursive
}
returnValue = new UpperBoundedWildcardType(upperJavaBounds);
}
} else {
assert upperBounds == null || upperBounds.isEmpty() || (upperBounds.size() == 1 && TypeDescription.Generic.OBJECT.equals(upperBounds.get(0))) : "Unexpected upper bounds: " + upperBounds + "; lower bounds: " + lowerBounds;
// Lower bounded.
assert lowerBounds.size() == 1 : "Unexpected size in lower bounds: " + lowerBounds;
returnValue = new LowerBoundedWildcardType(toType(lowerBounds.get(0))); // XXX recursive
}
break;
default:
throw new IllegalArgumentException("Unexpected type: " + type);
}
}
return returnValue;
}
No, you can only convert a Type to a TypeDescription.Generic but there is no option to do it the other way. The easiest option to emulate this would probably be to define a class that defines a field of the given Type, to load this class and to read the field type using Java reflection.
The reason Byte Buddy cannot convert a description to a Type is that Byte Buddy abstracts out class loaders and that type variables might be detached from their declaring source.
/*
* Notes here
*/
package billboardsign;
/**
*
* #author John Parada
*/
import java.util.ArrayList;
public class Billboard
{
private String text;
private ArrayList<String> messages = new ArrayList<String>();
public Billboard()
{
messages.add("Happy New Year");
messages.add("Happy Holidays");
messages.add("Team Pizza");
messages.add("Game On");
messages.add("Let's Go Team");
}
public ArrayList<String> getMessages()
{
return messages;
}
public void setMessages(String msg)
{
messages.add(msg);
}
public boolean isEmpty()
{
return text == null || text.isEmpty();
}
public String substring(int begin, int end)
{
if (begin >= 0 && end < text.length())
{
return text.substring(begin, end);
}
else
return null;
}
//add the method Reverse here
// THIS CODE IS NO GOOD!for (int count = text.length() - 1; count >= 0; count-- )
//FOLLOW UP LINE System.out.printf( "%s ", text.charAt( count ) );
public String reverse()
{
if (isEmpty())
return null;
else
{
char[] chars = text.toCharArray();
//create antoher arrayList
char[] reverse = new char[chars.length];
for (int i = chars.length - 1, j = 0; i < 0; i--, j++)
{
reverse[j] = chars[i];
}
return new String(reverse);
}
}
//add the method Replace string here
public String replace(char oldChar, char newChar)
{
return text.replace(oldChar, newChar);
}
//add the method displayInfo here
public void displayInfo()
{
System.out.printf("\n%s\nMessage", messages);
}
}
/*
* Notes on the Billboard Project
*/
package billboardsign;
/**
*
* #author John Parada
*/
import java.util.Scanner;
public class BillboardSign
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Billboard newBillboard = new Billboard(); //default constructor
//Menu
int choose_again = 1;
int choiceNumber;
Scanner newInput = new Scanner(System.in);
while (choose_again > 0 )
{
//list options to user
System.out.println ("\nPlease choose a number between 1 and 6 to choose an\n"
+ "option for the Messages Board to display: "
+ "\n1) Display Default Message 1"
+ "\n2) Display Default Message 2"
+ "\n3) Display Default Message 3"
+ "\n4) Display Default Message 4"
+ "\n5) Display Default Message 5"
+ "\n6) Enter a New Message"
+ "\n7) Reverse a Message"
+ "\n8) Replace a Message - Substring"
+ "\n9) Exit Program");
//get the user to input a selection
System.out.print ("\nPlease Enter Your Selection: ");
choiceNumber = newInput.nextInt();
//use switch statement to help with thieir choice input
switch (choiceNumber)
{
case 1:
//execute get() and displayInfo() method for default Message 1
//newBillboard = Billboard();
messages.get(0);
displayInfo();
break;
case 2:
//execute get() and displayInfo() method for default Message 2
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 3:
//execute get() and displayInfo() method for default Message 3
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 4:
//execute get() and displayInfo() method for default Message 4
newBillboard = Billboard();
Billboard = displayInfo();
break;
case 5:
displayInfo();
break;
case 6:
//execute set() and displayInfo() methods to create a new message
break;
case 7:
//execute reverse message method
break;
case 8:
//execute Replace message - Substring method
case 9:
//Dispaly to the user that they have chose to exit
System.out.print ("\nYou have chosen to cancel and exit. \n");
System.exit(0);
}
//prompt user for antother selection? (Contiune=1 and Exit= -1)
System.out.println();
System.out.print ("\nIf you would like to select another animal enter 1 or if your are done enter -1: ");
choose_again = newInput.nextInt();
}
}
private static void displayInfo() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
In short, when the user selects 1, he or she is supposed to get the first element of the ArrayList(0). When he or she selects 2, they will get the second element in the ArrayList(1). I need to invoke the get method, and use the displayInfo of the Billboard.
Thank you in advance for any and all help.
Regards,
John Parada
do something likewise,
case 1:
newBillboard.getMessages().get(0);
...
case 1:
newBillboard.getMessages().get(1);
....
And so on.
your getMessages() method is returning an arraylist so either you should have in an arraylist variable in your main class like this
ArrayList<String> messages = newBillboard.getMessages();
and then call it like this
case 1:
//execute get() and displayInfo() method for default Message 1
//newBillboard = Billboard();
System.out.println (messages.get(0));
//displayInfo();
break;
or you can simply call it like this
newBillboard.getMessages.get(0);//here 0 is for first element
and there is no need to get an object of your class in every case
and what is the need of displayInfo is unclear so if you tell why have you added that i might see to it.
So I am trying to create a "TestClass" that basically holds onto my Matcher, actual results, error message, and test label.
However, I am slowly starting to realize this might not be possible but I feel like it should be.
Perhaps someone here can help.
Here is what I am trying to do:
public void runTest(){
Assert.assertThat(testLabel + " " + errorMessage, actualResult, testToRun);
}
or, since I am doing Selenium Tests, something like this:
public void runTestAsWebElement(String attributeToCheck){
Object tempActualResult;
switch (attributeToCheck.toLowerCase()){
case "isdisplayed()":
case "isdisplayed":
tempActualResult = ((WebElement) actualResult).isDisplayed();
break;
case "isselected":
case "isselected()":
tempActualResult = ((WebElement) actualResult).isSelected();
break;
case "isenabled":
case "isenabled()":
tempActualResult = ((WebElement) actualResult).isEnabled();
break;
case "text":
tempActualResult = ((WebElement) actualResult).getText();
break;
default:
tempActualResult = ((WebElement) actualResult).getAttribute(attributeToCheck);
}
Assert.assertThat(testLabel + " " + errorMessage, tempActualResult, testToRun);
}
However, I am wondering, will the matchers be able to figure out that the Actual Result is a String or Boolean? Or will it always fail since both objects are being compared as Objects, rather than strings (not sure how the underlying code would be executed).
Any advice on how to properly handle this situation would be much appreciated!
Just to give some context - I am currently writing code like this:
Switch(whatToTest){
case "eye portfolio tests":
customCheckErrorMessages.add("The Eye Portfolio header doesn't match expected user's value");
customCheckActualResults.add(eyePortfolioPage.eyePortfolioAccountHeader);
customCheckExpectedResults.add(holder);
customCheckTests.add(containsString(holder));
customTestAttributeToTest.add("text");
break;
//just showing what my step looks like
}
String actualResult = "";
for(int x = 0; x < customCheckErrorMessages.size(); x++){
try{
switch (customTestAttributeToTest.get(x)){
case "text":
actualResult = customCheckActualResults.get(x).getText();
break;
default:
actualResult = customCheckActualResults.get(x).getAttribute(customTestAttributeToTest.get(x));
break;
}
}catch (IndexOutOfBoundsException e){
//Assuming this field wasn't actually entered. Defaulting to getText
actualResult = customCheckActualResults.get(x).getText();
}
System.out.println("Additional Test #" + (x+1));
Assert.assertThat(customCheckErrorMessages.get(x) + " Expected: \"" + customCheckExpectedResults.get(x)
+ "\", Actual: \"" + customCheckActualResults.get(x).getText().trim(),
actualResult.trim(),
customCheckTests.get(x));
}
I would like to write code like this:
switch(whatIWantToTest){
case "transaction tests":
customTests.add(new TestClass("There should be at least one transaction appearing on the page", //error Message
"Looking For Transactions:", //Test Label
myOrdersPage.transactions.size(), //Actual Result
greaterThanOrEqualTo(1))); //Test to run (should contain expected result)
//Just showing what my step looks like
}
for (TestClass test : customTests){
test.runTest();
}
Here is the code I decided to use. If anyone has a better suggestion I would love to hear it :)
private String testType;
public String errorMessage, testAttribute;
public WebElement actualResult;
public List<WebElement> actualResults;
public String providedStringValue = null;
public Boolean providedBooleanValue = null;
public Matcher testToRun;
public int attempts = 1;
//Empty Constructor
public TestCase() {
errorMessage = "";
testType = "";
actualResult = null;
actualResults = null;
testToRun = null;
providedStringValue = null;
providedBooleanValue = null;
}
//Run Test as a String check
public TestCase(String errorMessage, String providedResult, Matcher testToRun){
this.errorMessage = errorMessage;
providedStringValue = providedResult;
testType = "String";
this.testToRun = testToRun;
}
//Run Test as a Boolean check
public TestCase(String errorMessage, Boolean providedResult, Matcher testToRun){
this.errorMessage = errorMessage;
providedBooleanValue = providedResult;
testType = "Boolean";
this.testToRun = testToRun;
}
//Run Test on a WebElement
public TestCase(String errorMessage, String testAttribute, WebElement actualResult, Matcher testToRun) {
this.errorMessage = errorMessage;
testType = "WebElement";
this.testAttribute = testAttribute;
this.actualResult = actualResult;
this.testToRun = testToRun;
}
//Run Test on a List<WebElement>
public TestCase(String errorMessage, String testAttribute, List<WebElement> actualResults, Matcher testToRun) {
this.errorMessage = errorMessage;
testType = "List";
this.testAttribute = testAttribute;
this.actualResults = actualResults;
this.testToRun = testToRun;
}
public void clearTest() {
errorMessage = "";
testType = "";
testAttribute = "";
actualResult = null;
actualResults = null;
testToRun = null;
providedStringValue = null;
providedBooleanValue = null;
}
public void runTest() {
try {
if (testType.equalsIgnoreCase("WebElement")) {
runTestAsWebElement(testAttribute);
} else if (testType.equalsIgnoreCase("List")) {
runTestAsList(testAttribute);
} else if(testType.equalsIgnoreCase("Boolean")){
runTestAsBooleanCheck();
} else if(testType.equalsIgnoreCase("String")){
runTestAsStringCheck();
} else {
Assert.fail("Don't know how to run this test type");
}
} catch (StaleElementReferenceException e) {
if (attempts < 5) {
System.out.println("StaleElementReferenceException - Running test again");
attempts++;
runTest();
return;
} else {
throw e;
}
}
attempts = 1;
}
private void runTestAsStringCheck(){
Assert.assertThat(errorMessage, providedStringValue, testToRun);
}
private void runTestAsBooleanCheck(){
Assert.assertThat(errorMessage, providedBooleanValue, testToRun);
}
//Sometimes the actualResult is a WebElement which means the value to check is wrapped within another value.
private void runTestAsWebElement(String attributeToCheck) {
Object actualResultHolder;
switch (attributeToCheck.toLowerCase()) {
case "exists":
case "present":
try{
actualResult.isDisplayed(); //Forcing WebElement to look for element. If throws exception, element not found
actualResultHolder = true;
} catch (NoSuchElementException e){
actualResultHolder = false;
}
break;
case"display":
case "displayed":
case "isdisplayed()":
case "isdisplayed":
try{
actualResultHolder = actualResult.isDisplayed();
} catch (NoSuchElementException e){
System.out.println("Element not found");
throw e;
//actualResultHolder = false;
}
break;
case "selected":
case "isselected":
case "isselected()":
actualResultHolder = actualResult.isSelected();
break;
case "enabled":
case "isenabled":
case "isenabled()":
actualResultHolder = actualResult.isEnabled();
break;
case "text":
actualResultHolder = actualResult.getText().trim();
break;
default:
if (attributeToCheck.contains("css: ")) {//In case we want to test the css attribute instead of the HTML attribute
attributeToCheck = attributeToCheck.split("css: ")[1];
actualResultHolder = actualResult.getCssValue(attributeToCheck);
} else {
actualResultHolder = actualResult.getAttribute(attributeToCheck);
}
}
Assert.assertThat(errorMessage + "\n Actual Result = \"" + actualResultHolder + "\" ", actualResultHolder, testToRun);
}
private void runTestAsList(String attributeToCheck) {
switch (attributeToCheck.toLowerCase()) {
case "size":
case "size()":
Assert.assertThat(errorMessage, actualResults.size(), testToRun);
break;
default:
//do nothing - Test has to do with the list of elements.
Assert.assertThat(errorMessage, actualResults, testToRun);
}
}
Then, if for whatever reason I need some other type of test I just add it to the class.
I need a function that will convert a type to a string, for example:
Dim foo as Dictionary(of Dictionary(of Integer, String), Integer)
Debug.WriteLine(TypeToString(GetType(foo)))
In the debug output, I'd expect to see something equivalent to:
Dictionary(of Dictionary(of Integer, String), Integer)
Here's some extension methods I use to do what you ask, but it's in C# and generate C#.
You can either keep it in C#, but change the output to VB.Net or do a full conversion to VB.Net if you like.
public static string ToCode(this Type #this)
{
string #return = #this.FullName ?? #this.Name;
Type nt = Nullable.GetUnderlyingType(#this);
if (nt != null)
{
return string.Format("{0}?", nt.ToCode());
}
if (#this.IsGenericType & !#this.IsGenericTypeDefinition)
{
Type gtd = #this.GetGenericTypeDefinition();
return string.Format("{0}<{1}>", gtd.ToCode(), #this.GetGenericArguments().ToCode());
}
if (#return.EndsWith("&"))
{
return Type.GetType(#this.AssemblyQualifiedName.Replace("&", "")).ToCode();
}
if (#this.IsGenericTypeDefinition)
{
#return = #return.Substring(0, #return.IndexOf("`"));
}
switch (#return)
{
case "System.Void":
#return = "void";
break;
case "System.Int32":
#return = "int";
break;
case "System.String":
#return = "string";
break;
case "System.Object":
#return = "object";
break;
case "System.Double":
#return = "double";
break;
case "System.Int64":
#return = "long";
break;
case "System.Decimal":
#return = "decimal";
break;
case "System.Boolean":
#return = "bool";
break;
}
return #return;
}
public static string ToCode(this IEnumerable<Type> #this)
{
var #return = "";
var ts = #this.ToArray<Type>();
if (ts.Length > 0)
{
#return = ts[0].ToCode();
if (ts.Length > 1)
{
foreach (Type t in ts.Skip<Type>(1))
{
#return = #return + string.Format(", {0}", t.ToCode());
}
}
}
return #return;
}
Isn't foo.GetType().ToString() acceptable for you? In the example case it will return
System.Collections.Generic.Dictionary`2[System.Collections.Generic.Dictionary`2[System.Int32,System.String],System.Int32]