ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ECLIPSE IDE - "Test First Methods"- An Introduction to Test Driven Design (TDD)

Updated on August 8, 2014

The Tutorial Prequel to this Tutorial

The prequel to the material this tutorial will present is contained in "ECLIPSE IDE - JUnit Testing a Key Element Agile Software Development for JAVA (Part I)" and its follow on "ECLIPSE IDE - JUnit Testing a Key Element Agile Software Development for JAVA (Part II)". It would be most beneficial to review those tutorials before preceding with this one.

Benefits of Test Driven Development

The benefits of Test Driven Development is that in considering first what a method is supposed to do divorces the developer from too early on becoming distracted by implementation details or obstacles. Thinking on scratch paper of what function(s) one would like a method to perform is a way to start. Then determine how the output or results could be displayed or reused by other components of the application or other applications. When this is done, methods which are more generalized and adaptable for future use result. The tests developed have an added benefit in that they portray an accurate and detailed specification of and documentation for our code.

Agile programming techniques emphasize an incremental and iterative process which tightly couples development and testing. When one implements code using the "test first" approach one is really following the Agile programming philosophy.

The Test to be Constructed - Using the toSring() Method

The test which will be constructed in this example compares the output of the method to be deployed (the actual output) with the desired output (the expected output)

To demonstrate the "test first" method we will be using the ECLIPSE toString() method.

The toString() method is inherited by all classes from the Object class. The toString() method produces a string representation of an object.

We will use the ECLIPSE scrapbook page to demonstrate this. Our example will also reinforce some previous concepts about using this valuable prototyping feature.


Looking at the toString() Output Produced by Default

Let's look at the output produced by the toString() method inherited from the Object class.

The steps to perform utilizing the scrapbook are as follows;

Step 1: Create a scrapbook page called tostringexample by following the menu steps,

File > New> Other > Scrapbook page and entering the name of your project. and click on Enter. A view opens for entering statements, as we have seen in a previous tutorial. We will be using the BillingAddress class previously created The following snapshot illustrates several JAVA statements which we will execute from the scrapbook page:

  • creating a new object of the class BillingAddress
  • initializing several fields with there respective "setter" methods
  • calling the toString() default method to display a string representtion of the object.

Step 2: Highlight the text entered. Now note the output.

Whoa!!!? !! What happened. We got "tripped up" because one important detail was forgotten. Remember, the scrapbook page is outside the package so the class BillingAddress is unknown. In previous lessons, the import statement was discussed. Our problem is corrected easily by clicking on the icon for "Sets the Import Declaration for Running Code" and following the steps to add the tutorial package to the snapshot page.

The code now can be successfully executed, but the results don't appear very useful. For this reason

Scrapbook Input to Test the toString() Method

We create a new object of the class BillingAddress and enter values for several fields before calling the default toString() method.
We create a new object of the class BillingAddress and enter values for several fields before calling the default toString() method.

The Runtime Error in Our First Attempt

Because tthe scrapbook code exists outside the package, the BillingAddress class is unknow. When we run this example, the message indicates that the class cannot be resolved.
Because tthe scrapbook code exists outside the package, the BillingAddress class is unknow. When we run this example, the message indicates that the class cannot be resolved.

The "Set Import Declaration" Icon Location

The location of the "Set Import Declaration" sometimes baffles developers. It is at the far right in this illustration.
The location of the "Set Import Declaration" sometimes baffles developers. It is at the far right in this illustration.

Correcting the Problem: Setting the Import Class

Select the "Set Import Class Declarations", then select "Add Package", begin typing, "org" and ECLIPSE will help by present a list, select your tutorial package.
Select the "Set Import Class Declarations", then select "Add Package", begin typing, "org" and ECLIPSE will help by present a list, select your tutorial package.

The toString() Default Method Output

The output of the toString() method inherited from the Object class is illustrated in the next snapshot. From a practical point of view this is not really very helpful. Developers will write their own version of the method. Which is what we will be doing.

toString() Output

As noted above the output is not very useful.
As noted above the output is not very useful.

Creating an "Overiding" toString() Method

We want to have a more useful toString() method? So, how is that accomplished? We rewrite our own!

When a method is created this is meant to be used rather than the method inherited from the superclass, the process is known as overriding the method.

Following the "test first" Methodology

Athough writing the new, overriding toString() method could be immediately begun, the approach taken here will demonstrate the "test first" methodology. In which we:

  • consider what this new toString() method should do. That is what output would we like it to produce.
  • write the test case for the new toString() method
  • then, and only then, write the new toString() method
  • finally test the method

Writing the Test Method

The test method can naturally be added to our test cases file previously created. The code we created is as follows:

@Test
public void testToString() {
BillingAddress ba4 = new BillingAddress();
ba4.setCompanyName("Toni Styles, Inc.");
ba4.setCity("Scranton");
ba4.setState("Pennsylvania");
String testString = "Company: Toni Styles, Inc. in Scranton, Pennsylvania";
assertEquals(testString, ba4.toString());
}

It consists of:

  • the @Test annotation, which helps ECLIPSE JUnit know it's a test
  • the declaration of the method name, testToString with a public type
  • creation of ba4, a new object of the type BillingAddress
  • several set calls to ":setters'" to initialize fields
  • a call to the static method assertEquals to test whether the toString() method (not yet written) satisfies the requirements.

Note that the statement:

String testString = "Company: Toni Styles, Inc. in Scranton, Pennsylvania"; actually is specification and documents for our code. It states exactly what we want the toString() method to produce.

Note also, the specification presented here will remain accurate. If the toString() method passes now and later fails in the future, the test will fail. If we want all of our tests to pass the specification in the testToString() will have to be updated, keeping the specification and documentation aspect current and accurate.

Running the JUnit test at this point results in a error since the toString() method has yet to be written.

A Preliminary Run Results in A Failure

Since the overriding method has yet to be written, the test fails as the program is still referencing the default toString method.
Since the overriding method has yet to be written, the test fails as the program is still referencing the default toString method.

Implementing the Overriding toString() Mehtod

The following code is used for the overriding toString method:

public String toString() {
return "Company: " + this.getCompanyName() + " in " + this.getCity() + ", " + this.getState();
}

Our toString() method is rather simple it involve simple text pre- and post- fixed to "getters" for the fields to be compared in the test method.

Note in the edit view for this method, a green arrow. Hovering over the arrow will give the developer "heads-up" that this is an override method.

Note also, although we could have used field names rather than "getters" in formatting the return statement, allowing our fields to remain "hidden" has advantages. If the name fields were to be replaced with a first, middle, last name set of fields, this changes would not impact this statement.

Once this code is implemented, out test runs successfully.

Success!

Once the new code for the overriding toString function is set, the test cases run successfully.
Once the new code for the overriding toString function is set, the test cases run successfully.

What if there was an error?

The error can be looked at in two ways from the JUnit test view. On the far right of the screen there are two icons for the error display. The following snapshots illustrate this.

Two Ways of Looking at the Failure

Sometimes a little hard to read. One can always toggle to the other presentation by toggling between the two icons on the far right of the view.
Sometimes a little hard to read. One can always toggle to the other presentation by toggling between the two icons on the far right of the view.
A more convenient view for comparing text errors.
A more convenient view for comparing text errors.

Wrap Up and What's Up Next

In this tutorial, the "test first" methodology was investigated. First, the test case was created and then the actual method of built. Success and failure results were presented. New Terminology of Agile software development, Test Driven Development (TDD), method overriding were introduced.

In the next lesson we will be adding a new class to our project continuing the use of "test first" practices.

Meeting Expectations?

Cast your vote for Did this tutorial meet your expectations and needs?

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)