iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17846

how to test string creation? when the string is created using data from db

I created an app to tweet twice automatically each day. Now I'm told to write the test files.

The tweet itself is generated by strings and also data from a database.

String actual = genTweet();        
String expected = "Company Most Active ($Vol. in Millions) | SCZZL $19.5 | HUTC $18.1 | TSCDY $18.0 | TOELY $16.2 | GBGM $15.7 | More at: http://www.website.com/home";
assertEquals(expected, actual);

I'm thinking, how the heck does one even test this? The dollar values and the symbols change constantly, so every time actual != expected.

Any suggestion will be greatly appreciated!!!

Upvotes: 0

Views: 61

Answers (3)

Alexander
Alexander

Reputation: 23537

Let's say this is your genTweet() function:

public String getTweet(List<Activity> activities) {
  String tweetText = "Company Most Active ($Vol. in Millions)";
  for (Activity activity : activities) {
    tweetText = String.format("%s | %s $%.02f", tweetText, activity.getCompanyName(), activity.getMoney());
  }
  return tweetText;
}

Now, you can control the information your genTweet() function uses. In production, it will get populated from database or from any other storage engine. In development mode, from your local database snapshot.

During testing you usually populate them in your setUp() method.

// setUp()
List<Activity> activities = new List();
activities.add(new Activity("A", 1.10));
activities.add(new Activity("B", 2.209));

// Expected
String expected = "Company Most Active ($Vol. in Millions) | A $1.10 | B $2.21";

// Real
String real = genTweet(activities);

assertEquals(expected, real);

I was gonna talk about Mock Objects. But this is another intuitive way of seeing it.

Upvotes: 0

Dave Rager
Dave Rager

Reputation: 8160

You don't typically run tests against a production server. Instead, use a test server with predicable data completely under your control.

Upvotes: 2

Jeremy
Jeremy

Reputation: 2908

How about some regex in which you match but exclude the variable parts.

Upvotes: 1

Related Questions