Welcome!

Java IoT Authors: Carmen Gonzalez, Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz

Related Topics: Java IoT

Java IoT: Article

Java Product Review: What to Do If Your Code Has No Tests

Tools that practically write tests by themselves

When MailReader - an example application bundled with the Struts Action framework - was created six years ago, most Java developers had yet to discover unit testing. Consequently neither the Struts framework nor the MailReader were created test-first. Since then, we've bolted a few unit tests onto the Action framework, but the MailReader for Struts 1.2 still has no developer tests at all.

Over the last 10 years, testing has become more popular with developers. Much of this popularity can be attributed to the JUnit framework: a simple effective tool for many teams. But JUnit isn't enough. It makes writing tests easier, but we still have to write the tests. Many of us despair at the notion of writing even more code to test the application code we're already writing. What we need are tools that can write most of the tests for us.

Software Agitation
Software Agitation exercises and analyzes Java binary code and generates observations about how the code behaves. Developers can quickly create tests based on these observations, often without writing any new code. This article walks through using Agitator to create unit tests for the Struts MailReader application.

The flagship software agitation tool is Agitator by Agitar Software. The tool rapidly creates observations of code behavior, and helps the developer determine if the code is working as expected or see if Agitation has revealed unexpected behavior.

From within the Eclipse IDE, we can promote a valid observation to a unit test, or we can trace through the code to change the behavior. If the application code is valid, but the range of acceptable values needs to be adjusted to demonstrate correct behavior, we can assign custom factories to a parameter. Along with factories, Agitar provides for automatic "Domain Experts" that we can use to test code peculiar to our own API or to test code peculiar to frameworks like Struts.

Getting Started
After launching Agitator's version of Eclipse, we can create a new project using the "Java Project with Agitation" template. For this project, we point Eclipse at the root of the Struts 1.2 source tree. We have a library of JARs for the Struts 1.2.8 distribution, which are easy to add to the Eclipse Build Path as "External JARs" along with a reference to the servlet JAR for Java 2.3.

The one other thing we have to do is unselect irrelevant packages as source folders. In Struts 1.2, the MailReader source is mixed in with packages for the rest of the framework distribution. In the end, we have two source folders: src/example and web/example.

We can open the "Agitator" view from the menu bar, and "Agitate" the package containing the five MailReader business classes [org.apache.struts.webapp.example.memory].

A New York minute later, Agitator has done its thing. Three classes are in good shape, with 100% code coverage. Two of the five classes were flagged with warning symbols. The MemoryDatabasePlugIn class weighed in at 70% coverage. The key class, MemoryUserDatabase, had 38% coverage. The code coverage for each is shown in Table 1.

Let's start with the low-hanging fruit and review the three classes with 100% coverage: MemorySubscription, MemoryUser and TestUserDatabase.

MemorySubscription and MemoryUser represent database entities. Being standard JavaBeans, these classes were easy for Agitator to test. Each of the JavaBean properties has a standard unit test to ensure that the field is set by the parameter.

The only two methods lacking tests are the constructor and toString. The constructor is simple, but, still, Agitator has generated some essential tests like:

this.getHost() == host
this.getUser() == user
Table 2 - MemorySubscription Constructor Method
    public MemorySubscription(MemoryUser user, String host) {
       super();
       this.user = user;
       this.host = host;
    }

We can mark these as unit tests to prevent simple silly mistakes like assigning a parameter back to itself.

The toString method creates a textual representation of the class. The method looks hard to test with a known set of input data. For now, we can change the method's property to "Exclude from testing."

    public String toString() {

      StringBuffer sb = new StringBuffer("<subscription host=\"");
      sb.append(host);
// ...
      if (username != null) {
        sb.append(" username=\"");
        sb.append(username);
        sb.append("\"");
    }
    sb.append(">");
    return (sb.toString());

Reviewing observations for the other classes and methods, we find several other assertion candidates. Each of these candidates corresponds to assertions that we might have made in a conventional JUnit test. For example, setting the pathname property also sets the pathnameNew and pathnameOld fields. We didn't have to express that fact to Agitator. On its own, the software observed that

@EQUALS( this.pathnameOld, "database.xml.old" )

All we have to do is confirm that the observation is an assertion that we should test. If we were writing a JUnit test, we'd have typed-out code like:

assertEquals( this.pathnameOld, "database.xml.old" );

With Agitator in play, we just point and click.

Not bad. After only a few minutes of clicking around, we have almost 80 test points. Perhaps most important, these test points will automatically evolve with the code - something that hand-coded tests can never do.

Now, what's the problem with the other two classes that had less than 100% coverage?

Agitator displays a legend next to the lines in a class to show how often each line of code is being reached by Agitation, or if the line was even reached in the first place. In the case of MemoryUserDatabase, we can see that there are a lot of red lines after an input-output call, indicating that the code isn't being reached. Clicking through, it's easy to see why many of the Exceptions were being thrown: "File Not Found."

The "Memory" implementation of the MailReader data access object loads a list of Users and their e-mail Subscriptions from an XML document into an object graph stored in main memory. (Hence, the package name.) The file wasn't found because Agitator had no way of guessing the right file name. For now, I mark the problematic classes or methods "Exclude from testing" - at least until we can learn a bit more about Agitator.

Excluding the eight input-output members lowered the overall test coverage. But, even so, in only a few minutes, we were able crank up Agitator for the first time, create over 80 test points, and yield a test coverage of around 40%.

Agitating Struts
The Agitar website hosts a 47-minute "webinar" on its Struts Expert. I watch this and skim the documentation.

Now that we've had a taste of Domain Experts, let's put the Struts Expert through its paces.

LogonAction
The webinar mentioned the standard Struts Expert, which can be found and enabled on Agitator/Plugin Experts menu. Eclipse is not displaying any red marks, so the code seems to be compiling. Let the Struts Agitation begin!

After Agitating the MailReader code base with the Struts Expert enabled, a number of red marks popped up in the Package Explorer. Drilling down, we find error icons next to the Action execute methods. The pop-up hint explains that the Struts configuration can't be found. Meanwhile, the Console view contains several warnings that a ServletContext can't be found either.

Returning to the Agitator menu, we find the likely item "Create J2EE Environment." A wizard leads us through creating a default environment, and even includes a "Test" button so we can check our work.

Now that we have a J2EE environment, for good measure, we pop back to the PlugIn Experts menu and enable the J2EE expert too. After another Agitation, there are still red marks, but the messages are functional rather than systemic, with remarks like "Coverage failed" and "Outcome failed".

Opening up LogonAction, we find the Struts We already have 67% coverage, and the execute method has partitions for the various Struts outcomes: registration, logoff, logon, success, and welcome. Several class invariants were generated, but only "this.getServlet() != null" looks like a worthwhile assertion.


More Stories By Ted Husted

Ted Husted (http://husted.com/ted/) is a software engineer and an active member of several open source projects hosted by the Apache Software Foundation, including Struts and iBATIS. His books include JUnit in Action, Struts in Action, and Professional JSP Site Design. Ted is also a consultant for Agitar Software, Inc.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
SYS-CON Events announced today that Hitachi Data Systems, a wholly owned subsidiary of Hitachi LTD., will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City. Hitachi Data Systems (HDS) will be featuring the Hitachi Content Platform (HCP) portfolio. This is the industry’s only offering that allows organizations to bring together object storage, file sync and share, cloud storage gateways, and sophisticated search an...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
NHK, Japan Broadcasting, will feature the upcoming @ThingsExpo Silicon Valley in a special 'Internet of Things' and smart technology documentary that will be filmed on the expo floor between November 3 to 5, 2015, in Santa Clara. NHK is the sole public TV network in Japan equivalent to the BBC in the UK and the largest in Asia with many award-winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology and will be covering @ThingsExpo Silicon Val...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software in the hope of capturing value in IoT. Although IoT is relatively new in the market, it has already gone through many promotional terms such as IoE, IoX, SDX, Edge/Fog, Mist Compute, etc. Ultimately, irrespective of the name, it is about deriving value from independent software assets participating in an ecosystem as one comprehensive solution.
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
SYS-CON Events announced today that Juniper Networks (NYSE: JNPR), an industry leader in automated, scalable and secure networks, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Juniper Networks challenges the status quo with products, solutions and services that transform the economics of networking. The company co-innovates with customers and partners to deliver automated, scalable and secure network...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
With billions of sensors deployed worldwide, the amount of machine-generated data will soon exceed what our networks can handle. But consumers and businesses will expect seamless experiences and real-time responsiveness. What does this mean for IoT devices and the infrastructure that supports them? More of the data will need to be handled at - or closer to - the devices themselves.
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
NHK, Japan Broadcasting, will feature the upcoming @ThingsExpo Silicon Valley in a special 'Internet of Things' and smart technology documentary that will be filmed on the expo floor between November 3 to 5, 2015, in Santa Clara. NHK is the sole public TV network in Japan equivalent to the BBC in the UK and the largest in Asia with many award-winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology and will be covering @ThingsExpo Silicon Val...
The 20th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held June 6-8, 2017, at the Javits Center in New York City, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal ...