reset password
Author Message
rabbott
Posts: 1649
Posted 12:19 Jan 27, 2014 |

A Car class.

/**
 * A Car class for exercise P 4.1
 */
public class Car
{
    // instance variables

    public double fuelEfficiency;
    public double pricePerGallon;
    private double initialCost;

    public static void main(String[] args) {
        Car hybridCar = new Car(75, 4, 27000);
        Car nonHybridCar = new Car(20, 4, 18000);
        double cOfOH = hybridCar.costOfOwnership(5, 15000);
        double cOfONH = nonHybridCar.costOfOwnership(5, 10000);
        System.out.printf("Hybrid: %,6.0f; NonHybrid: %,6.0f", cOfOH, cOfONH);
    }

    /**
     * Constructor for objects of class Car4_10
     */
    public Car(double fuelEfficiency, double pricePerGallon, double initialCost)
    {
        // initialize instance variables
        this.fuelEfficiency = fuelEfficiency;
        this.pricePerGallon = pricePerGallon;
        this.initialCost = initialCost;
    }

    public double costOfOwnership(double years, double resaleValue) {
        // compute and return the cost of ownership based on miles driven and
        // the difference between the initial cost and the resale value.
        // capital cost + operational cost
        double capitalCost = initialCost - resaleValue;
        double operationalCost = 15000 * years * getCostPerMile();
        return capitalCost + operationalCost;
    }

    public double getCostPerMile()
    {
        return pricePerGallon/fuelEfficiency;
    }

}

 

A JUnit test class

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * The test class CarTest.
 *
 * @author  (your name)
 * @version (a version number or a date)
 */
public class CarTest
{
    /**
     * Default constructor for test class CarTest
     */
    public CarTest()
    {
    }

    /**
     * Sets up the test fixture.
     *
     * Called before every test case method.
     */
    @Before
    public void setUp()
    {
    }

    /**
     * Tears down the test fixture.
     *
     * Called after every test case method.
     */
    @After
    public void tearDown()
    {
    }

    @Test
    public void testGetCostPerMile() {
        Car car = new Car(25, 4.00, 25000);
        double costPerMile = car.pricePerGallon/car.fuelEfficiency;
        assertEquals(costPerMile, car.getCostPerMile(), 0.001);
    }

    @Test
    public void testCostOfOwnership() {
        Car car = new Car(25, 4.00, 25000);
        double cOfO = car.costOfOwnership(5, 15000);
        assertEquals(10000 + 15000 * 5 * car.getCostPerMile(), cOfO, 0.001);
    }
}

 

Last edited by rabbott at 12:29 Jan 27, 2014.