We help IT Professionals succeed at work.

Why is my JUnit class not compiling? And what can I do to make it work properly?

Eindoofus
Eindoofus asked
on
Here is the class I am testing:

public class Crate implements Cargo
{
    private String identifier;
    
    private double weight;

    public Crate(String idIn, double wgtIn) throws InvalidArgumentException
    {
        setIdentifier(idIn);
        setWeight(wgtIn);
    }
    
    @Override
    public String getIdentifier()
    {
        return identifier;
    }

    private void setIdentifier(String idIn) throws InvalidArgumentException
    {
        if (idIn == null || idIn.isEmpty() || idIn.length() > 20)
            throw new InvalidArgumentException("Invalid identifier passed to Crate.setIdentifier: " + idIn);
        identifier = idIn;
    }

    @Override
    public double getWeight()
    {
        return weight;
    }
    
    private void setWeight(double weightIn) throws InvalidArgumentException
    {
        if (weightIn <= 0.0)
            throw new InvalidArgumentException("Invalid weight passed to Crate.setWeight: " + weightIn);
        weight = weightIn;
    }
}

Open in new window


And here is the test class for the Crate class that I wrote:

public class CrateTest {
    
    public CrateTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }
    
    @Before
    public void setUp() {
    }
    
    @After
    public void tearDown() {
    }

    /**
     * Test of getIdentifier method, of class Crate.
     */
    @Test
    public void testGetIdentifier() {
        Crate ct;
        
        // Positive test
        try {
            ct = new Crate("id", 3.0); 
            assertEquals("errortxt", "id", ct.getIdentifier());
            assertEquals("errortxt", 3.0, ct.getWeight(), 0.00001);
        } 
        catch (Exception e) {
            fail("Legitimate values were rejected when sent to constructor" + e.getMessage());
        }
        
        // Negative test for null String
        try {
            ct = new Crate(null, 3.0);            
            fail("errortxt");
        } 
        catch (InvalidArgumentException e) {
            assertEquals("errortxt", "Invalid identifier passed to Crate.setIdentifier: " + null, e.getMessage());
            assertEquals("errortxtONE", 0.0, ct.getWeight(), 0.00001);
        }
        
        // Negative test for empty String
        try {
            ct = new Crate("", 3.0);            
            fail("errortxt");
        } 
        catch (InvalidArgumentException e) {
            assertEquals("errortxt", "Invalid identifier passed to Crate.setIdentifier: " + "", e.getMessage());
            assertEquals("errortxtTWO", 0.0, ct.getWeight(), 0.00001);
        }
        
    }

    /**
     * Test of getWeight method, of class Crate.
     */
    @Test
    public void testGetWeight() {
    }
}

Open in new window


When I attempt to compile my test the compiler complains that "variable ct may not have been initialized" on the line with "assertEquals("errortxtONE", 0.0, ct.getWeight(), 0.00001);" yet, the line with "assertEquals("errortxtTWO", 0.0, ct.getWeight(), 0.00001);" doesn't come back with an error message.

The compiler outputs the following:

Testsuite: shipexample.implementors.CrateTest
Tests run: 2, Failures: 0, Errors: 1, Time elapsed: 0.053 sec

Testcase: testGetIdentifier(shipexample.implementors.CrateTest):	Caused an ERROR
Uncompilable source code - variable ct might not have been initialized
java.lang.RuntimeException: Uncompilable source code - variable ct might not have been initialized
	at shipexample.implementors.CrateTest.testGetIdentifier(CrateTest.java:64)


Test shipexample.implementors.CrateTest FAILED
test:
Deleting: Omitted\TEST-shipexample.implementors.CrateTest.xml
BUILD SUCCESSFUL (total time: 3 seconds)

Open in new window


What am I doing wrong? Why can't I use "ct.getWeight()"? And what do I need to do to my code to make this work properly? I need to somehow check to make sure the state of the Crate class "weight" data member didn't change on lines  "assertEquals("errortxtONE", 0.0, ct.getWeight(), 0.00001);"and "assertEquals("errortxtTWO", 0.0, ct.getWeight(), 0.00001);"



Comment
Watch Question

In line 27 above in your CrateTest class, try putting:

Crate ct = null;

Open in new window


instead of

Crate ct;

Open in new window

Author

Commented:
It works but I was told that I need to test the state of the object after it's creation. Doesn't that defeat the purpose since it's not testing the state of the object in the try block?
Not really, because null is not an object and you would get null pointer exceptions in your assertions if the object was not actually created.  
Awarded 2011
Awarded 2011

Commented:
When ct = new ...
Statement is in the same brace as Assert(...) Then compiler is sure that ct will be initialized;
If they are in separate braces then compiler cannot be sure that initialization will happen befire use;
There fore compiler complains;
If you assign =null as suggested at the very top, as was suggested then comnpiler will be happy
On a slightly unrelated note to the original question, its better to break all three of those try/catch blocks into separate test methods so that you are only testing one piece of functionality in each test.  Also, this looks more like you're testing the constructor, as opposed to the getIdentifier() method.  You should probably rename your test methods appropriately.

public class CrateTest {
    
    public CrateTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }
    
    @Before
    public void setUp() {
    }
    
    @After
    public void tearDown() {
    }

    /**
     * Test of getIdentifier method, of class Crate.
     */
    @Test
    public void testConstructor() {
		Crate ct = new Crate("id", 3.0); 
		assertEquals("errortxt", "id", ct.getIdentifier());
		assertEquals("errortxt", 3.0, ct.getWeight(), 0.00001);
    }

	@Test
	public void testConstructor_NullIdentifier() {
        // Negative test for null String
        try {
            ct = new Crate(null, 3.0);            
            fail("errortxt");
        } 
        catch (InvalidArgumentException e) {
            assertEquals("errortxt", "Invalid identifier passed to Crate.setIdentifier: " + null, e.getMessage());
            assertEquals("errortxtONE", 0.0, ct.getWeight(), 0.00001);
        }
    }

	@Test
	public void testConstructor_EmptyIdentifier() {
        // Negative test for empty String
        try {
            ct = new Crate("", 3.0);            
            fail("errortxt");
        } 
        catch (InvalidArgumentException e) {
            assertEquals("errortxt", "Invalid identifier passed to Crate.setIdentifier: " + "", e.getMessage());
            assertEquals("errortxtTWO", 0.0, ct.getWeight(), 0.00001);
        }
    }

    /**
     * Test of getWeight method, of class Crate.
     */
    @Test
    public void testGetWeight() {
    }
}

Open in new window


Question; why are you declaring your own InvalidArgumentException class?  Is this something that has been mandated?  Normally some combination of the existing java.lang exceptions are more than sufficient for argument checking and provide better information to the user.  Your above example would be much more descriptive if you change the test for a valid identifier to:

if (idIn == null)
	throw new NullPointerException("identifier is null");
if (idIn.isEmpty())
    throw new IllegalArgumentException("identifier is empty")
// Use this instaed of the above if you want to catch all-whitespace identifiers
//if (idIn.trim().isEmpty())
//	throw new IllegalArgumentException("identifier is empty");
if (idIn.length() > 20)
	throw new IllegalArgumentException("identifier must be < 20 characters");

Open in new window