I wrote a program called Geometry that finds the volume and surface area of a sphere, cone and cylinder. I have to use JUnit 4 Testing to test the separate classes. I have written the following code but when I run the test it says it fails even though my program runs correctly. What is wrong?

package edu.waketech.lbgladson;

import static org.junit.Assert.*;

import org.junit.Assert;
import org.junit.Test;

public class SphereVolumeTest
{
	@Test	public void getVolume()
	{
		Sphere sphere = new Sphere(5);
		Assert.assertEquals("523.5987755982989", sphere.getVolume(5));
				
		}
	}
Assert.assertEquals("523.5987755982989", sphere.getVolume(5));

Equal means equal, but double/float value is an estimate. As a result, the different value could occurs at the level of epsilon. What you need to do is to give a margin of error for computation. If it is double, give it a 1x10^-10 or so.

How do I give it a margin of error and implement that into the code?

Assert that the absolute value of the difference is less than your threshold.

Where would I insert that...I was thinking

Assert.assertEquals("523.5987755982989", sphere.getVolume(5)), Math.abs(523.5987755982989 - sphere.getVolume(5) < .5);

but that is obviously not correct.

assertEquals() would not apply here since you aren't testing equality. Take a look at the other assert methods and find one that could assert your condition.

JUnit is designed to handle this. There's an extra optional parameter just for floating point values:

Assert.assertEquals(523.5987755982989, sphere.getVolume(5), 0.00000000000001);

(Make sure that 'getVolume' returns a 'double' value.)

(Note: Also, it's silly for the Sphere class to take the radius as both a constructor parameter and a parameter to the 'getVolume' method. I'll leave it as an exercise for the student to figure out which of the two is more appropriate. ;-)

commented: Good info. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.