jeudi 16 avril 2015

How to compare String representations of doubles if it ends in .00

I am currently writing test cases for a ContentProvider in my application (which is a checkbook recording app) and I am having a test fail when it is comparing double values. The best way to illustrate this is with code. I have this function that returns ContentValues for an account object to be inserted into the database:



private ContentValues getAccountContentValues(){
String testName = "Capital One";
double testStartingBalance = 3000.00;

ContentValues accountValues = new ContentValues();
accountValues.put(AccountEntry.COLUMN_NAME, testName);
accountValues.put(AccountEntry.COLUMN_BALANCE, testStartingBalance);

return accountValues;
}


Inside a function testInsertReadProvider() I have the following code, to insert that account:



// Get Account values and write them
ContentValues accountValues = getAccountContentValues();
Uri accountInsertUri =
mContext.getContentResolver().insert(AccountEntry.CONTENT_URI, accountValues);
long accountRowId = ContentUris.parseId(accountInsertUri);

// Verify we got a row back
assertTrue(accountRowId > 0);

// A cursor is the primary interface to the query results
Cursor cursor = mContext.getContentResolver().query(
AccountEntry.CONTENT_URI, // Table name
null, // columns to be returned. Null returns all columns
null, // Columns for where clause
null, // Values for where clause
null // Sort order
);

// Validate the information read from the database.
validateCursor(cursor, accountValues);
cursor.close();


The validate cursor function takes a cursor and a ContentValues and loops through them using a map to compare each value. This is a strategy I learned from following a Udacity tutorial on creating Android applications, so maybe there is a better way to compare them instead of as strings, but it looks like this:



void validateCursor(Cursor valueCursor, ContentValues expectedValues){
assertTrue(valueCursor.moveToFirst());

Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet();

for(Map.Entry<String, Object> entry : valueSet){
String columnName = entry.getKey();
int idx = valueCursor.getColumnIndex(columnName);
assertFalse(idx == -1);
String expectedValue = entry.getValue().toString();
assertEquals(expectedValue, valueCursor.getString(idx));
}
valueCursor.close();
}


The test is failing when the assertEquals() line is called, and I get the following error message:



junit.framework.ComparisonFailure: expected:<3000[.0]> but was:<3000[]>



It looks like the cursor.getString() method is truncating the decimal places if they are equal to 0. If I try this test using a value of 3000.01 it works fine. Is SQLite responsible for dropping the unnecessary zeroes? Can I change the assertEquals() in some way so that those two values are treated the same?


Aucun commentaire:

Enregistrer un commentaire