Thursday, November 24, 2011

Junit Testing - Basic Tutorial

1. Introduction

1.1. Unit Testing

A unit test is a piece of code written by a developer that tests a specific functionality in the code which is tested. Unit tests can ensure that functionality is working and can be used to validate that this functionality still works after code changes.

1.2. Unit Testing with JUnit

JUnit 4.x is a test framework which uses annotation to identify the methods which contain tests. JUnit assumes that all test methods can be performed in an arbitrary order. Therefore tests should not depend other tests.
To write a test with JUnit
  • Annotate a method with @org.JUnit.Test
  • Use a method provides by JUnit to check the expected result of the code execution versus the actual result

You use a tool like Eclipse or the class "org.junit.runner.JUnitCore" to run the test.

2. Installation of JUnit

If you use Eclipse you can use the integrated JUnit in Eclipse for your testing.
If you want to control the used JUnit library explicitly, download JUnit4.x.jar from the JUnit website . The download contains the "junit-4.*.jar" which is the JUnit library. Add this library to your Java project and add it to the classpath.

3. JUnit with Eclipse

3.1. Preparation

Create a new project de.vogella.junit.first . We want to create the unit tests in a separate folder. The creation of an separate folder for the test is not mandatory. But it is good advice to keep the test coding separate from the normal coding. Typically you would even create a separate project for the test classes, we skip this step to make this example simpler.
Create therefore a new source folder test via right mouse click on your project, select properties and choose the "Java Build Path". Select the tab source code.


Press "Add folder" then then press "Create new folder". Create the folder "test".


3.2. Create a Java class

Create a package de.vogella.junit.first and the following class.

     
package de.vogella.junit.first;

public class MyClass {
 public int multiply(int x, int y) {
  return x / y;
 }
}
    

3.3. Create a JUnit test

Select your new class, right mouse click and select New → JUnit Test case . Select "New JUnit 4 test". Also set the the source folder to test, so that your test class gets created in this folder.


Press next and select the methods which you want to test.


If you have not yet added JUnit in your classpath, Eclipse will prompt you, if JUnit t should be added to the classpath.


Create a test with the following code.

     
package de.vogella.junit.first;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyClassTest {

 @Test
 public void testMultiply() {
  MyClass tester = new MyClass();
  assertEquals("Result", 50, tester.multiply(10, 5));
 }
}
    

3.4. Run your test via Eclipse

Right click on your new test class and select Run-As → Junit Test .




The test should be failing (indicated via a red bar). This is due to the fact that our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green light.
If you have several tests you can combine them into a test suite. All test in this test suite will then be executed if you run the test suite. To create a new test suite, select your test classes Right mouse click → New → Other → JUnit → Test Suite .


Select next and select the methods you would like to have test created for.
Change the coding to the following to make your test suite run your test. If you later develop another test you can add it to @Suite.SuiteClasses .

package mypackage;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses( { MyClassTest.class })
public class AllTests {
}

   

3.5. Run your test via code

You can also run your test via your own coding. The class org.junit.runner.JUnitCore provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of type org.junit.runner.Result . This object can be used to retrieve information about the tests and provides information about the failed tests.
Create in your "test" folder a new class MyTestRunner with the following coding. This class will execute your test class and write potential failures to the console.

package de.vogella.junit.first;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyTestRunner {
 public static void main(String[] args) {
  Result result = JUnitCore.runClasses(MyClassTest.class);
  for (Failure failure : result.getFailures()) {
   System.out.println(failure.toString());
  }
 }
}

   

4. JUnit (more) in Detail

4.1. Static imports with Eclipse

JUnit uses a lot of static methods and Eclipse cannot automatically import static imports. You can make the JUnit test methods available via the content assists.
Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.


You can now use Content Assist (Ctrl+Space) to add the method and the import.
I suggest to add at least the following new members.
  • org.junit.Assert.assertTrue
  • org.junit.Assert.assertFalse
  • org.junit.Assert.assertEquals
  • org.junit.Assert.fail

4.2. Annotations

The following give an overview of the available annotations in JUnit 4.x

Table 1. Annotations
Annotation Description
@Test public void method() Annotation @Test identifies that this method is a test method.
@Before public void method() Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)
@After public void method() Test method must start with test
@BeforeClass public void method() Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database
@AfterClass public void method() Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database
@Ignore Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.
@Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception
@Test(timeout=100) Fails if the method takes longer then 100 milliseconds


4.3. Assert statements

The following gives an overview of the available test methods:

Table 2. Test methods
Statement Description
fail(String) Let the method fail, might be usable to check that a certain part of the code is not reached.
assertTrue(true); True
assertsEquals([String message], expected, actual) Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays
assertsEquals([String message], expected, actual, tolerance) Usage for float and double; the tolerance are the number of decimals which must be the same
assertNull([message], object) Checks if the object is null
assertNotNull([message], object) Check if the object is not null
assertSame([String], expected, actual) Check if both variables refer to the same object
assertNotSame([String], expected, actual) Check that both variables refer not to the same object
assertTrue([message], boolean condition) Check if the boolean condition is true.

Wednesday, November 23, 2011

Eclipse - Open an Existing Java Project

Create a new Java project in Eclipse. This will create a src folder (to contain your source files).
Also create a lib folder (the name isn't that important, but it follows standard conventions).
Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).
Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)
Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)
Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.
The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). IF you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.
Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.
That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

Java - SOAP Http Post

Use the examples below as a template for posting an xml SOAP message to my document/literal operation style web service. Also, you can customize the message you send to the remote procedure (in bold).
Example 1-11. Upload the SOAP message: PostXml.java
import java.net.*;
import java.io.*;

public class PostXml {

  public static void main(String[] args) {
  
    try {
     /* String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + 
 "<env:Envelope " + 
   "env:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " + 
   "xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" " + 
   "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + 
   "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
   "<env:Header/>" +
          "<env:Body>" +
     "<ans1:readLS xmlns:ans1=\"http://phonedirlux.homeip.net/types\">" +
       "<String_1 xsi:type=\"xsd:string\">your message or e-mail</String_1>" +
     "</ans1:readLS>" +
   "</env:Body>" +
        "</env:Envelope>"; */
  
     String xmldata = "<s12:Envelope xmlns:s12='http://www.w3.org/2003/05/soap-envelope'>" +
       "<s12:Body> " +
        "<ns1:GetCitiesByCountry xmlns:ns1='http://www.webserviceX.NET'>" +
          "<ns1:CountryName xmlns:ns1='http://www.webserviceX.NET'>Pakistan</ns1:CountryName>" +
        "</ns1:GetCitiesByCountry>" +
      "</s12:Body>" +
      "</s12:Envelope>";
      
      
      //Create socket
      //String hostname = "www.pascalbotte.be";
     String hostname = "www.webservicex.com";
      int port = 80;
      InetAddress  addr = InetAddress.getByName(hostname);
      Socket sock = new Socket(addr, port);
   
      //Send header
      String path = "/rcx-ws/rcx";
      BufferedWriter  wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
      // You can use "UTF8" for compatibility with the Microsoft virtual machine.
     // wr.write("POST " + path + " HTTP/1.0\r\n");
      wr.write("POST /globalweather.asmx HTTP/1.1\r\n");      
      //wr.write("Host: www.pascalbotte.be\r\n");
      wr.write("Host: www.webservicex.com\r\n");
      
      
      wr.write("Content-Length: " + xmldata.length() + "\r\n");
      //wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
      wr.write("Content-Type: application/soap+xml; charset=\"utf-8\"\r\n");
      wr.write("\r\n");
   
      //Send data
      wr.write(xmldata);
      wr.flush();
   
     // Response
      BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      String line;
      while((line = rd.readLine()) != null)
 System.out.println(line);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


Tuesday, November 22, 2011

Object Oriented Design - Anti-Patterns

Anemic Domain Model: The use of domain model without any business logic. The domain model's objects cannot guarantee their correctness at any moment, because their validation and mutation logic is placed somewhere outside (most likely in multiple places).
BaseBean: Inheriting functionality from a utility class rather than delegating to it
Call super: Requiring subclasses to call a superclass's overridden method
Suppose there is a class for generating a report about the inventory of a video rental store. Each particular store has a different way of tabulating the videos currently available, but the algorithm for generating the final report is the same for all stores. A framework that uses the call super anti-pattern may provide the following abstract class (in C#)
abstract class ReportGenerator {
    public virtual Report CreateReport() {
        // Generate the general report object
        // ...
        return new Report(...);
    }
}
A user of the class is expected to implement a subclass like this:
class ConcreteReportGenerator : ReportGenerator {
    public override Report CreateReport() {
        // Tabulate data in the store-specific way
        // ...
        // Design of this class requires the parent CreateReport() function to be called at the
        // end of the overridden function. But note this line could easily be left out, or the
        // returned report could be further modified after the call, violating the class design
        // and possibly also the company-wide report format.
        return base.CreateReport();
    }
}
A preferable interface looks like this:
abstract class ReportGenerator {
    public Report CreateReport() {
        Tabulate();

        // Generate the general report object
        // ...
        return new Report(...);
    }

    protected abstract void Tabulate();
}
An implementation would override this class like this:
class ConcreteReportGenerator : ReportGenerator {
    protected override void Tabulate() {
        // Tabulate data in the store-specific way
        // ...
    }
}
Circular dependency: Introducing unnecessary direct or indirect mutual dependencies between objects or software modules
Constant interface: Using interfaces to define constants
public interface Constants {
         public static final double PI = 3.14159;
        public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
 public class Calculations implements Constants {
         public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

God object: Concentrating too many functions in a single part of the design (class)
Object cesspool: An object pool is a set of initialized objects that are kept ready to use, rather than allocated and destroyed on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object, it returns it to the pool, rather than destroying it
Object orgy: Failing to properly encapsulate objects permitting unrestricted access to their internals. Unrestricted access makes it hard for the reader to reason about the behavior of an object. This is because direct access to its internal state means any other part of the system can manipulate it, increasing the amount of code to be examined, and opening the door to future abuse.
Poltergeists: Objects whose sole purpose is to pass information to another object
Sequential coupling: A class that requires its methods to be called in a particular order
Yo-yo problem: A structure (e.g., of inheritance) that is hard to understand due to excessive fragmentation. Most practices of object-oriented programming recommend keeping the inheritance graph as shallow as possible, in part to avoid this problem. The use of composition instead of inheritance is also strongly preferred, although this still requires that a programmer keep multiple class definitions in mind at once. More generally, the yo-yo problem can also refer to any situation where a person must keep flipping between different sources of information in order to understand a concept.

Facade pattern

From Wikipedia, the free encyclopedia
The facade pattern is a software engineering design pattern commonly used with Object-oriented programming. The name is by analogy to an architectural facade.
A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make code that uses the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).
An Adapter is used when the wrapper must respect a particular interface and must support a polymorphic behavior. On the other hand, a facade is used when one wants an easier or simpler interface to work with.

Structure

FacadeDesignPattern.png
Facade
The facade class abstracts Packages 1, 2, and 3 from the rest of the application.
Clients
The objects using the Facade Pattern to access resources from the Packages.

Example

This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).
/* Complex parts */
 
class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}
 
class Memory {
    public void load(long position, byte[] data) { ... }
}
 
class HardDrive {
    public byte[] read(long lba, int size) { ... }
}
 
/* Facade */
 
class Computer {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;
 
    public Computer() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }
 
    public void startComputer() {
        cpu.freeze();
        memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
        cpu.jump(BOOT_ADDRESS);
        cpu.execute();
    }
}
 
/* Client */
 
class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.startComputer();
    }
}

Inheritace and ERD

You have three alternatives to translate class hierarchies into relational tables: - Create only a table for the superclass (all attributes and associations of subclasses are moved to the table corresponding to the superclass with the possibility of taking a NULL value) - Create only tables for the subclasses: All attributes and associations of the superclass are repeated in each subclass - Create tables both for the superclass and for each of the subclasses. In this case, the PK of the subclasses is at the same table a FK to the superclass (this ensures that all identifiers in a subclass table correspond to an existing identifier in the superclass table. A join between both tables allows to recover the full information of the element)
The best strategy depends on the problem (for instance, the number of attributes in each class, the number of levels in hierarchy, whether the hierarchy is disjoint or not,...)

java Static methods vs singletons

From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader business, you avoid some tricky problems, especially when you try to reload the web application.

You can find "some blogger" who pretty much dislikes anything. There's nothing wrong with static methods, so long as any state they operate on is local to the method/passed in with each call (same caveat applies for instance methods on a singleton).
Either approach should be fine, just pick the one you prefer. As a general rule of thumb, go with static methods if your singleton instance would not be holding any state that is potentially mutable at runtime. Otherwise, if the singleton is meant to hold state and not just serve as a repository for a handful of utility methods, then make it a singleton.
The only halfway reasonable argument against using static methods that I have come across is that static methods are problematic to mock-out for unit-testing purposes. But my guess is that you are probably not doing mock unit-testing, and I think the value of testing with mock objects is generally overstated when you look at the value that comes out of it relative to the amount of work that goes into setting up the test case(s).