13 Replies - 491 Views - Last Post: 27 November 2019 - 01:12 PM Rate Topic: -----

#1 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 06:38 AM

Hello, I am having difficulty with three sections of my unit test the testGetMinTermQuote(), testGetMaxTermQuote(), testGetRateByPos() and testToString() where I am getting feedback I have not tested all possibilities for the else if statement. Below is the code to my class and what I have so far for the tests I am having trouble with.

Thanks!


import java.util.ArrayList;

/**
 * Creates and manages a collection of LifeRates.
 *
 * @author Doyt Perry/Russell Roeder
 * @version Fall 2019
 */
public class LifeRatesManager
{
    // instance variables
    private ArrayList<LifeRates> rates;

    // constants
    /**
     * Tolerance variable when comparing floating point values in sort method.
     */
    public static final double SORT_DELTA = .001;

    /**
     * Constructor for objects of class LifeRatesManager.
     */
    public LifeRatesManager()
    {
        this.rates = new ArrayList<LifeRates>();
    }

    /**
     * Return the the number of LifeRates objects in the collection.
     *
     * @return int          the number of LifeRates objects in the collection.
     *
     */
    public int getCount()
    {
        return rates.size();
    }

    /**
     * Add a LifeRates object to the collection.
     *
     * @param  inRate       the LifeRates object.
     *
     */
    public void addRate(LifeRates inRate)
    {
        LifeRates tmp = new LifeRates(inRate);
        this.rates.add(tmp);
    }

    /**
     * Obtain a LifeRates object from the collection based on index.
     *
     * @param  inIndex      the index of the element in the collection.
     * @return LifeRates    the LiferRates object from the collection,
     *                      (returns null if index not valid).
     *
     */
    public LifeRates getRate(int inIndex)
    {
        if (inIndex >= 0 && inIndex < rates.size() - 1)
        {
            return this.rates.get(inIndex);
        }
        return null;
    }

    /**
     * Obtain a LifeRates object from the collection based on name.
     *
     * @param  inName       the name of candidate policy holder.
     * @return LifeRates    an object in the collection with that name.
     *                      (returns null if name not found).

     *
     */
    public LifeRates getRate(String inName)
    {
        for (int i = 0; i < rates.size() - 1; i++)
        {
            if (this.rates.get(i).getName().equalsIgnoreCase(inName))
            {
                return this.rates.get(i);
            }
        }
        return null;
    }

    /**
     * Remove a LifeRates object from the collection based on index.
     *
     * @param  inIndex      the index of the LifeRates to remove
     *                      (do nothing if index is invalid).
     *
     */
    public void deleteRate(int inIndex)
    {
        if (inIndex >= 0 && inIndex < rates.size())
        {
            this.rates.remove(inIndex);
        }
    }

   /**
     * Remmove a LifeRates object from the collection based on name.
     *
     * @param  inName       the name associated with the object to remove
     *                      (do nothing if name not found).
     *
     */
    public void deleteRate(String inName)
    {
        for (int i = 0; i < rates.size(); i++)
        {
            if (this.rates.get(i).getName().equalsIgnoreCase(inName))
            {
                this.rates.remove(inName);
            }
        }
    }

    /**
     * Return a new LifeRatesManager with the valid LifeRates of the
     *      collection ordered by ascending value of term rate.
     *
     * @return LifeRatesManager     a new collection containing LifeRates in
     *                              the collection with valid term rates,
     *                              sorted in ascending order by term rate.
     *
     * This method is based on the bblSort3 method
     * presented in Module 11.
     */
    public LifeRatesManager sortValidRates()
    {
        ArrayList<LifeRates> sortedRates = new ArrayList<LifeRates>();

        for (int i = 0; i < rates.size(); i++)
        {   
            if (this.rates.get(i).calcTermRate() != RateUtility.INVALID)
            {
                sortedRates.add(this.rates.get(i));
            }
        }
        for (int x = 0; x < sortedRates.size() - 1; x++)
        {
            for (int y = 0; y < sortedRates.size() - 1; y++)
            {
                if (sortedRates.get(y).calcTermRate() >
                    sortedRates.get(y + 1).calcTermRate())
                {
                    LifeRates tmp = sortedRates.get(y);
                    sortedRates.set(y, sortedRates.get(y + 1));
                    sortedRates.set(y + 1, tmp);
                }
            }
        }
        LifeRatesManager sortedManager = new LifeRatesManager();
        for (int z = 0; z < sortedRates.size(); z++)
        {
            sortedManager.addRate(sortedRates.get(z));
        }
        return sortedManager;
    }
    /**
     * Return a LifeRates object with the minimum term rate.
     *
     * @return LifeRates        an object in the collection
     *                          with the min term rate
     *                          (null if collection is empty).
     */
    public LifeRates getMinTermQuote()
    {
        // first sort the collection via a method call
        LifeRatesManager sortedManager = this.sortValidRates();

        if (sortedManager.getCount() == 0)
        {
            return null;   // there are no valid rates
        }
        else
        {
            // return the first (lowest rate)
            return new LifeRates(sortedManager.getRate(0));
        }
    }

    /**
     * Return a LifeRates object with the maximum term rate.
     *
     * @return LifeRates        an object in the collection
     *                          with the maximum term rate
     *                          (null if collection is empty).
     */
    public LifeRates getMaxTermQuote()
    {
        LifeRatesManager sortedManager = this.sortValidRates();

        if (sortedManager.getCount() == 0)
        {
            return null;
        }
        else
        {
            return new LifeRates(sortedManager.getRate(this.rates.size() - 1));
        }
    }


    /**
     * Build a String containing the state of the collection
     *      in the following format.
     * <pre>
       There are 4 policyholders
       1: Doe, Dan (quoted a term rate of 32.0)
       2: Kay, Karen (cannot quote a term rate)
       3: Lovelace, Ada (quoted a term rate of 74.482)
       4: Babbage, George (quoted a term rate of 338.805)
     * </pre>
     *
     * @return String  The state of the object.
     */
    public String toString()
    {
        String ratesString = "\nThere are " + this.rates.size() +
            " policyholders\n";

        int count = 1;
        for (int i = 0; i < this.rates.size(); i++)
        {
            String name = this.rates.get(i).getName();
            double quote = this.rates.get(i).calcTermRate();
            if (this.rates.get(i).calcTermRate() == RateUtility.INVALID)
            {
                ratesString += count + ":" + name + "(cannot quote)\n";
            }   
            else if (this.rates.get(i).calcTermRate() 
                != RateUtility.INVALID)
            {
                ratesString += count + ":" + name + 
                    "(Quoted a term rate of " + quote + ")\n";
            }
            count++;
        }
        return ratesString;
    }

}




/**
     * Test get rate by postion.
     */
    @Test
    public void testGetRateByPos()
    {
        LifeRates rateTest = quotes.getRate(quotes.getCount() - 1);
        assertNotNull(rateTest);
        assertFalse(rateTest.getEstimator().isSmoker());
        assertEquals('F', rateTest.getEstimator().getGender());
        assertEquals(62, rateTest.getEstimator().getAge());
        assertTrue(rateTest.getEstimator().isHighRisk());
        assertEquals(1, rateTest.getEstimator().getNumTickets());
        assertEquals("Good", rateTest.getEstimator().getHealth());
        assertEquals(325000.0, rateTest.getFaceValue(), DELTA);
        assertEquals("Tyler, Rachel", rateTest.getName());
        //test invalid positions
        assertNull(this.quotes.getRate(-1));
        assertNull(this.quotes.getRate(quotes.getCount()));

    }
/**
     * Test get minimum term rate.
     */
    @Test
    public void testGetMinTermQuote()
    {
        LifeRatesManager buffer = new LifeRatesManager();
        assertNull(buffer.getMinTermQuote());
        
        //int count = 0;
        assertEquals(0, buffer.getCount());
        
    }
    /**
     * Test get maximum term rate.
     */
    @Test
    public void testGetMaxTermQuote()
    {
        LifeRatesManager buffer = new LifeRatesManager();
        LifeRatesManager lifeRates2 = new LifeRatesManager();
        assertNotNull(lifeRates2);
    }


    /**
     * Test toString.
     */
    @Test
    public void testToString()
    {
        String rateString = quotes.toString();

        assertTrue(rateString.contains("There are 6"));
        assertFalse(rateString.contains("0:"));
        assertTrue(rateString.contains("Gutterman, Donald"));
        assertTrue(rateString.contains("52.0"));
        assertTrue(rateString.contains("Van Camp, Fred"));
        assertTrue(rateString.contains("Tyler, Rachel"));
        assertTrue(rateString.contains("6:"));
        assertTrue(rateString.contains("cannot quote"));
        assertTrue(rateString.contains("(Quoted a term rate of "));
        assertNotNull(rateString);

        // test on an empty collection
        LifeRatesManager emptyQuotes = new LifeRatesManager();
        rateString = emptyQuotes.toString();
    }
}




Is This A Good Question/Topic? 0
  • +

Replies To: Assistance with writing Unit Tests for lab

#2 NormR   User is offline

  • D.I.C Lover
  • member icon

Reputation: 797
  • View blog
  • Posts: 6,062
  • Joined: 25-December 13

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 07:13 AM

Quote

I am getting feedback ...

Can you copy and paste here the text of any messages you are getting?
Was This Post Helpful? 0
  • +
  • -

#3 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 07:32 AM

You are just being told that your testing should test every return value. So if you have a method,

    public LifeRates getMaxTermQuote()
    {
        LifeRatesManager sortedManager = this.sortValidRates();

        if (sortedManager.getCount() == 0)
        {
            return null;
        }
        else
        {
            return new LifeRates(sortedManager.getRate(this.rates.size() - 1));
        }
    }



For example. You should have a test validating that you get null back, and another that returns a new LifeRates object.
Was This Post Helpful? 0
  • +
  • -

#4 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:13 AM

View PostNormR, on 27 November 2019 - 07:13 AM, said:

Quote

I am getting feedback ...


I am getting on the testGetRateByPos

no exception message
---
java.lang.Assertionerror
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:621)
at org.junit.Assert.assertNotNull(Assert.java:631)
at LifeRatesManagerTest.testGetRateByPos(LifeRatesManagerTest.java:158)


I am having a hard time trying yo get to that point... I have tried a couple of things but it won't compile due to a method or code being incorrect. Can you point me in the right direction of how to test each of them? do I need to set it as 0 and then assertEquals?

Thank you

View Postastonecipher, on 27 November 2019 - 07:32 AM, said:

You are just being told that your testing should test every return value. So if you have a method,

    public LifeRates getMaxTermQuote()
    {
        LifeRatesManager sortedManager = this.sortValidRates();

        if (sortedManager.getCount() == 0)
        {
            return null;
        }
        else
        {
            return new LifeRates(sortedManager.getRate(this.rates.size() - 1));
        }
    }



For example. You should have a test validating that you get null back, and another that returns a new LifeRates object.





I am having a hard time trying yo get to that point... I have tried a couple of things but it won't compile due to a method or code being incorrect. Can you point me in the right direction of how to test each of them? do I need to set it as 0 and then assertEquals?

Thank you
Was This Post Helpful? 0
  • +
  • -

#5 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:14 AM

Whats the entire test suit code?

Comment out all but one test for the time being, when that single test works start adding to it, but post the entire suit for now.

The error is because the Assert is failing and the first line,

LifeRates rateTest = quotes.getRate(quotes.getCount() - 1);

Where does quotes come from? A unit test should be self contained other than the setUp which is just to bootstrap a few things that are needed across the class being tested.
Was This Post Helpful? 0
  • +
  • -

#6 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:16 AM

View Postastonecipher, on 27 November 2019 - 08:14 AM, said:

Whats the entire test suit code?

Comment out all but one test for the time being, when that single test works start adding to it, but post the entire suit for now.

The error is because the Assert is failing and the first line,

LifeRates rateTest = quotes.getRate(quotes.getCount() - 1);

Where does quotes come from? A unit test should be self contained other than the setUp which is just to bootstrap a few things that are needed across the class being tested.


I commented out every line above the test on an empty collection. None of them worked. At this point am I testing the right things for the testToString? I am at a loss.
Was This Post Helpful? 0
  • +
  • -

#7 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:18 AM

Post the entire testing class. I need to see what you are trying to do since I'm not looking over your shoulder.
Was This Post Helpful? 0
  • +
  • -

#8 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:19 AM

View Postastonecipher, on 27 November 2019 - 08:18 AM, said:

Post the entire testing class. I need to see what you are trying to do since I'm not looking over your shoulder.


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

/**
 * The test class LifeRatesManagerTest.
 *
 * @author Doyt Perry/Russell Roeder
 * @version Fall 2019
 */
public class LifeRatesManagerTest 
{
    // instance fields
    private LifeRatesManager quotes;
    private LifeRates lifeRates0;
    private LifeRates lifeRates1;
    private LifeRates lifeRates2;
    private LifeRates lifeRates3;
    private LifeRates lifeRates4;
    private LifeRates lifeRates5;
    private int count;

    /**
     * Tolerance variable when comparing floating point values.
     */
    public static final double DELTA = .01;

    /**
     * Default constructor for test class LifeRatesManagerTest.
     */
    public LifeRatesManagerTest()
    {
        // not used for this lab
    }

    /**
     * Sets up the test fixture.
     *
     * Called before every test case method.
     */
    @Before
    public void setUp()
    {
        this.quotes = new LifeRatesManager();

        // Non smoker, Male, 25, Low Risk, 0 tickets, Good health
        lifeRates0 = new
            LifeRates("Gutterman, Donald",
            new RateEstimator(false, 'M', 25, false, 0, "Good"),
            100000);
        this.quotes.addRate(lifeRates0);
        count++;

        // Smoker, Male, 55, High Risk, 1 ticket, Fair health
        lifeRates1 = new
            LifeRates("Van Camp, Fred",
            new RateEstimator(true, 'M', 55, true, 1, "Fair"),
            500000);
        this.quotes.addRate(lifeRates1);
        count++;

        // Non smoker, female, 24, Low Risk, 2 tickets, Poor health
        lifeRates2 = new
            LifeRates("Speigel, Lisa",
            new RateEstimator(false, 'F', 24, false, 2, "Bad"),
            110000);
        this.quotes.addRate(lifeRates2);
        count++;

        // Non smoker, Male, 25, Low Risk, 3 tickets, Good health
        lifeRates3 = new
            LifeRates("Lee, Kim",
            new RateEstimator(false, 'M', 25, false, 3, "Good"),
            110000);
        this.quotes.addRate(lifeRates3);
        count++;

        // Smoker, Male, 79, Low Risk, 0 tickets, Poor health
        lifeRates4 = new
            LifeRates("Flynn, Thomas",
            new RateEstimator(true, 'M', 79, false, 0, "Poor"),
            405000);
        this.quotes.addRate(lifeRates4);
        count++;

        // Non smoker, Female, 62, High Risk, 1 ticket, Good health
        lifeRates5 = new
            LifeRates("Tyler, Rachel",
            new RateEstimator(false, 'F', 62, true, 1, "Good"),
            325000);
        this.quotes.addRate(lifeRates5);
        count++;

    }

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

    /**
     * Test class constructor.
     */
    @Test
    public void testConstructor()
    {
        LifeRatesManager emptyQuotes = new LifeRatesManager();

        assertNotNull(emptyQuotes);
        assertEquals(0, emptyQuotes.getCount());
    }

    /**
     * Test get count.
     */
    @Test
    public void testGetCount()
    {
        LifeRatesManager emptyRatesTest = new LifeRatesManager();
        assertEquals(0, emptyRatesTest.getCount());
    }

    /**
     * Test add rate.
     */
    @Test
    public void testAddRate()
    {
        // begin: sample code for exercising addRate() method
        LifeRates rateTest = new LifeRates();
        quotes.addRate(rateTest);
        count++;
        
        assertEquals(count, this.quotes.getCount());
        assertNotNull(rateTest);
        assertNotSame(rateTest, quotes.getRate(count - 1));
        // end: sample code for exercising addRate() method
        
        
        //assertEquals(7, this.quotes.getCount()); 

    }

    /**
     * Test get rate by postion.
     */
    @Test
    public void testGetRateByPos()
    {
        LifeRates rateTest = quotes.getRate(quotes.getCount() - 1);
        assertNotNull(rateTest);
        assertFalse(rateTest.getEstimator().isSmoker());
        assertEquals('F', rateTest.getEstimator().getGender());
        assertEquals(62, rateTest.getEstimator().getAge());
        assertTrue(rateTest.getEstimator().isHighRisk());
        assertEquals(1, rateTest.getEstimator().getNumTickets());
        assertEquals("Good", rateTest.getEstimator().getHealth());
        assertEquals(325000.0, rateTest.getFaceValue(), DELTA);
        assertEquals("Tyler, Rachel", rateTest.getName());
        
        //test invalid positions
        assertNull(this.quotes.getRate(quotes.getCount() - 1));
        assertNull(this.quotes.getRate(quotes.getCount()));

    }

    /**
     * Test get rate by name.
     */
    @Test
    public void testGetRateByName()
    {
        LifeRates rateTest = quotes.getRate("Van Camp, Fred");

        assertNotNull(rateTest);
        assertNotSame(rateTest, lifeRates1);
        
        assertTrue(rateTest.getEstimator().isSmoker());
        assertEquals('M', rateTest.getEstimator().getGender());
        assertEquals(55, rateTest.getEstimator().getAge());
        assertTrue(rateTest.getEstimator().isHighRisk());
        assertEquals(1, rateTest.getEstimator().getNumTickets());
        assertEquals("Fair", rateTest.getEstimator().getHealth());
        assertEquals(500000.0, rateTest.getFaceValue(), DELTA);
        
        rateTest = this.quotes.getRate("Lee, Kim");

        assertNotNull(rateTest);
        assertNotSame(rateTest, lifeRates3);
        assertEquals("Lee, Kim", rateTest.getName());
        // test non existent name
        rateTest = this.quotes.getRate("Mouse, Mickey");
        assertNull(rateTest);

    }

    /**
     * Test delete rate by postion.
     */
    @Test
    public void testDeleteRateByPos()
    {
        this.quotes.deleteRate(2);
        count--;
        String name = "Speigel, Lisa";
        // test the existence of quote for "Lisa Speigel"
        assertNull(this.quotes.getRate(name));
        
        // test the number of quotes after delete
        assertEquals(5, this.quotes.getCount());
        // test the quote at index 2 after delete
        assertNull(quotes.getRate(name));
        // test deleting with an invalid index
        this.quotes.deleteRate(-1);
        //test the number of quotes after delete with an invalid index
        quotes.deleteRate(quotes.getCount());

        // test deleting a rate from an empty collection
        LifeRatesManager emptyQuotes = new LifeRatesManager();
        emptyQuotes.deleteRate(0);
    }

    /**
     * Test delete rate by name.
     */
    @Test
    public void testDeleteRateByName()
    {
        String name = "Speigel, Lisa";
        this.quotes.deleteRate(name);
        count--;
        
        this.quotes.deleteRate(name);
        assertNotNull(this.quotes.getRate(name));
        count--;
        LifeRates rateTest = this.quotes.getRate(2);
        assertNotNull(rateTest);
        
        // What's the name of the person at index 2?
        rateTest = this.quotes.getRate(3);
        assertEquals("Lee, Kim", rateTest.getName());

        // test deleting with name not in collection
        quotes.deleteRate("Mickey Mouse");

        // test deleting a rate from an empty collection
        LifeRatesManager emptyQuotes = new LifeRatesManager();
        emptyQuotes.deleteRate("Mickey Mouse");
    }

    /**
     * Test sort by rate.
     */
    @Test
    public void testSortByRate()
    {
        LifeRatesManager sortedManager = this.quotes.sortValidRates();

        assertEquals("Gutterman, Donald", sortedManager.getRate(0).getName());
        assertEquals("Lee, Kim", sortedManager.getRate(1).getName());
        assertEquals("Tyler, Rachel", sortedManager.getRate(2).getName());
        assertEquals("Van Camp, Fred", sortedManager.getRate(3).getName());
        //assertEquals("Flynn, Thomas", sortedManager.getRate(4).getName());

        // test sorting an empty collection
        LifeRatesManager emptyQuotes = new LifeRatesManager();
        sortedManager = emptyQuotes.sortValidRates();
        assertEquals(0, sortedManager.getCount());
    }

    /**
     * Test get minimum term rate.
     */
    @Test
    public void testGetMinTermQuote()
    {
        LifeRatesManager buffer = new LifeRatesManager();
        assertNull(buffer.getMinTermQuote());
        
        //int count = 0;
        assertEquals(0, buffer.getCount());
        
    }

    /**
     * Test get maximum term rate.
     */
    @Test
    public void testGetMaxTermQuote()
    {
        LifeRatesManager buffer = new LifeRatesManager();
        assertNotNull(buffer);
    }


    /**
     * Test toString.
     */
    @Test
    public void testToString()
    {
        String rateString = quotes.toString();

        assertTrue(rateString.contains("There are 6"));
        assertFalse(rateString.contains("0:"));
        assertTrue(rateString.contains("Gutterman, Donald"));
        assertTrue(rateString.contains("52.0"));
        assertTrue(rateString.contains("Van Camp, Fred"));
        assertTrue(rateString.contains("Tyler, Rachel"));
        assertTrue(rateString.contains("6:"));
        assertTrue(rateString.contains("cannot quote"));
        assertTrue(rateString.contains("(Quoted a term rate of "));
        assertNotNull(rateString);

        // test on an empty collection
        LifeRatesManager emptyQuotes = new LifeRatesManager();
        rateString = emptyQuotes.toString();
    }
}



Was This Post Helpful? 0
  • +
  • -

#9 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:27 AM

Automatically stands out as bad for a few reasons:

public class LifeRatesManagerTest 
{
    // instance fields
    private LifeRatesManager quotes;
    private LifeRates lifeRates0;
    private LifeRates lifeRates1;
    private LifeRates lifeRates2;
    private LifeRates lifeRates3;
    private LifeRates lifeRates4;
    private LifeRates lifeRates5;
    private int count;


So the first thing I see is, be concise with your tests. You are ONLY testing the LifeRatesManager, that means you should be mocking the LifeRates class, because it is not under test.

So, you want to mock the LifeRates class so you can focus just on the functionality of LifeRateManager. Look at Mockito on how to mock the classes that are not under test.


From there, each unit test should instantiate its own LifeRatesManager and test the specific functionality that test is for. Be specific and ensure that it ONLY tests a single outcome.
Was This Post Helpful? 0
  • +
  • -

#10 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:37 AM

I do have a LifeRates class. I guess I am confused as to how to get the start of testing each outcome in the methods. So on the getMaxTermQuote how would I test the null and other possible outcomes? do I need to set a variable in the test?

here is my LifeRates
/**
 * Class to generate quotes for Life Insurance.
 *
 * @author Doyt Perry/Russell Roeder
 * @version Fall 2019
 */
public class LifeRates
{
    // instance variables
    private String name;
    private RateEstimator estimator;
    private double faceValue;

    // constants

    /**
     * Term life base policy amount.
     */
    public static final double BASE_FACEVALUE = 100000.00;

    /**
     * Term life max policy amount.
     */
    public static final double MAX_FACEVALUE = 600000.00;

    /**
     * Term life max policy amount.
     */
    public static final int MAX_MONTHS = 240;

    /**
     * Term life to whole life conversion factor.
     */
    public static final double CONVERT_FACTOR = 2.64;

    /**
     * Surrender value compound rate.
     */
    public static final double COMPOUND_RATE = .05;

    /**
     * Months per year.
     */
    public static final int MONTHS_PER_YEAR = 12;

    /**
     * Table for determing discounts for term life policies.
     */
    public static final double[][] TERM_DISCOUNT =
    {{100000.01, 100.0}, {200000.0, 95.0}, {300000.0, 88.0}, {400000.0, 84},
        {500000.0, 80.0}, {600000.0, 75.0}};

    /**
     * Table for determing surrender value percentages.
     */
    public static final int[][] SURRENDER_PCTG =
    {{60, 0}, {120, 23}, {180, 48}, {240, 75}};

    /**
     * First constructor for objects of class LifeRates.
     */
    public LifeRates()
    {
        this.estimator = new RateEstimator();
        this.faceValue = 0.0;
        this.name = null;
    }

    /**
     * Second constructor for objects of class LifeRates.
     *
     * @param inName        name of the candidate policy holder.
     * @param inEstimator   a RateEstimator for the candidate policy holder.
     * @param inFaceValue   the face value for rate quote.
     */
    public LifeRates(String inName, RateEstimator inEstimator,
        double inFaceValue)
    {
        this.name = inName;
        this.estimator = inEstimator;
        this.faceValue = inFaceValue;
    }

    /**
     * Third constructor for objects of class LifeRates
     *      that creates a copy of the parameter.
     *
     * @param inRates       an instance of LifeRates.
     */
    public LifeRates(LifeRates inRates)
    {
        this.estimator = inRates.getEstimator();
        this.faceValue = inRates.getFaceValue();
        this.name = inRates.getName();
    }


    /**
     * Update name of the candidate policy holder.
     *
     * @param inName  name of the candidate policy holder.
     *
     */
    public void setName(String inName)
    {
        this.name = inName;
    }

    /**
     * Return name of the candidate policy holder.
     *
     * @return String  name of the candidate policy holder.
     *
     */
    public String getName()
    {
        return this.name;
    }

    /**
     * Update the estimator for the candidate policyholder.
     *
     * @param inEstimator  Policy candidate RateEstimator.
     *
     */
    public void setEstimator(RateEstimator inEstimator)
    {
        this.estimator = inEstimator;
    }

    /**
     * Return the estimator for the candidate policyholder.
     *
     * @return RateEstimator  estimator for the candidate policyholder.
     *
     */
    public RateEstimator getEstimator()
    {
        return this.estimator;
    }

    /**
     * Update the the face value for rate quote.
     *
     * @param inFaceValue   the face value for rate quote.
     *
     */
    public void setFaceValue(double inFaceValue)
    {
        this.faceValue = inFaceValue;
    }

    /**
     * Return the face value for rate quote.
     *
     * @return double  the face value for rate quote.
     *
     */
    public double getFaceValue()
    {
        return this.faceValue;
    }


    /**
     * Calculate term life rate.
     *
     * @return double  monthly rate for a term life policy.
     *
     */
    public double calcTermRate()
    {
        double rateFactor = 1.0;
        double baseRate = 0;
        
        //constants for discount table
        final int category = 0;
        final int factor = 1;
        
        //Is face value valid?
        if (this.faceValue < BASE_FACEVALUE || this.faceValue >= MAX_FACEVALUE)
        {
            return RateUtility.INVALID;
        }
        //get base rate
        baseRate = this.estimator.calcMonthlyRate();
        if (baseRate == RateUtility.INVALID)
        {
            return RateUtility.INVALID;
        }
        //find term discount factor
        int level = 0 ;
        while (this.faceValue >= TERM_DISCOUNT[level][category])
        {
            level++;
        }
        rateFactor = TERM_DISCOUNT[level][factor] / 100.0;
        //adjust baseRate
        baseRate = (baseRate + (baseRate * (faceValue - 100000) / 100000) 
            * rateFactor);
        
        return baseRate;

    }

    /**
     * Calculate the whole life rate.
     *
     * @return double  monthly rate for a whole life policy.
     *
     */
    public double calcWholeRate()
    {
        double tmp = this.calcTermRate();
        if (tmp == RateUtility.INVALID)
        {
            return RateUtility.INVALID;
        }
        else
        {
            return CONVERT_FACTOR * tmp;
        }
    }

    /**
     * Calculate whole life Surrender Value.
     *
     * @param   inMonths    months before before terminating;
     * @return  double      surrender Value for a whole life policy
     *
     */
    public double getSurrenderVal(int inMonths)
    {
        // constants for use in accessing the surrender pctg table
        final int category = 0;
        final int pctg = 1;

        // Surrender value percentage
        double surndrFactor = 0;
        // Base rate
        double baseRate = 0;
        // Surrender value
        double surndrVal = 0;

        // Get whole life base rate
        baseRate = this.calcWholeRate();
        
        // Test if rate is invalid
        if (baseRate == RateUtility.INVALID)
        {
            return RateUtility.INVALID;
        }

        // Check if termination month is valid
        // If less than 0, return 0;
        // if > MAX_MONTHS, return face value
        if (inMonths < 0)
        {
            return 0;
        }
        else if (inMonths > MAX_MONTHS)
        {
            return this.faceValue;
        }
        
        // Find the surrender value percentage
        int level = 0;
        while (inMonths > SURRENDER_PCTG[level][category])
        {
            level++;
        }
        surndrFactor = SURRENDER_PCTG[level][pctg];

        // Calculate surrender value
        surndrVal = (surndrFactor / 100) * baseRate * inMonths *
            Math.pow(1 + COMPOUND_RATE / MONTHS_PER_YEAR, inMonths);

        // Adjust the surrender value if it's greater than face value
        if (surndrVal > this.faceValue)
        {
            surndrVal = this.faceValue;
        }
        return surndrVal;
    }

    /**
     * Build a String containing object information.
     *
     * @return String  The state of the object.
     */
    public String toString()

    {
        String quote = "Policy quote information:\n";
        quote += "Name: " + this.getName() + "\n";
        quote += "Smoker: " + this.estimator.isSmoker() + "\n";
        quote += "Gender: " + this.estimator.getGender() + "\n";
        quote += "Age: " + this.estimator.getAge() + "\n";
        quote += "High Risk: " + this.estimator.isHighRisk() + "\n";
        quote += "Tickets: " + this.estimator.getNumTickets() + "\n";
        quote += "Health: " + this.estimator.getHealth() + "\n";
        quote += "Face Value: " + this.getFaceValue() + "\n";
        quote += "Monthly premium term: " + 
            String.format("%.3f", this.calcTermRate()) + "\n";
        quote += "Monthly premium whole: " + 
            String.format("%.3f", this.calcWholeRate()) + "\n";

        return quote;
    }
}



Was This Post Helpful? 0
  • +
  • -

#11 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 08:38 AM

The LifeRates class is irrelevant, it isnít being tested so it needs to be faked
Was This Post Helpful? 0
  • +
  • -

#12 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 3038
  • View blog
  • Posts: 11,669
  • Joined: 03-December 12

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 09:03 AM

I take it this is for a course assignment? Just wondering why you are not using interfaces for the objects.

public LifeRates(String inName, RateEstimator inEstimator, double inFaceValue)


For example should be,

public LifeRates(String inName, IRateEstimator inEstimator, double inFaceValue)


So that you can swap the implementation of RateEstimator.
Was This Post Helpful? 0
  • +
  • -

#13 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 12:43 PM

Yes, this is for a course. We get a package with some information and have to finish code, debug and write the unit tests. I have had trouble all year with the unit tests but have had stuff to build off of to complete them in the labs. This one has been more difficult for me and I am just spinning my tires.
Was This Post Helpful? 0
  • +
  • -

#14 rroeder86   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-November 19

Re: Assistance with writing Unit Tests for lab

Posted 27 November 2019 - 01:12 PM

I am getting an error of "This assertion uses only values known at compile time, so it cannot test any useful behavior exhibited by your code at run-time." on the test testDeleteRateByPos() where I am using the code
 	
         // test the number of quotes after delete  	
         assertEquals(5, this.quotes.getCount());


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1