Unit Testing and Coverage

Testing Happens at Multiple Levels

Different Perspectives

JUnit - Sample Test Class

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class PointTest {

    private Point testPoint;

    @BeforeEach
    void setUp() throws Exception {
        testPoint = new Point(5.0, 6.0);
    }

    @Test
    void testToString() {
        assertEquals("(5.0, 6.0)", testPoint.toString());
    }

}

Testing Example

public class Estimator {
    
    public static int totalCost(boolean fast, boolean good) {
        
        int total = 0;
        
        if (fast) {
            total += 5;
        }
        
        if (good) {
            total += 10;
        }
        
        return total;
    }
    
}

Method Coverage

Style Suggestion

Statement Coverage

Branch Coverage

Path Coverage

Path Coverage

Developing Test Cases

Socrative Quiz #1

Consider the following utility class and the proposed tests:

Select the best option. This test class provides…

  1. 100% method coverage.
  2. 100% method and statement coverage.
  3. 100% method, statement and branch coverage.
  4. 100% method, statement, branch and path coverage.

Socrative Quiz #2

Select the best option. This test class..

  1. Is broken! It provides good coverage, but the tests are incorrect.
  2. Is correct, but not high-quality.
  3. Is good! It contains no logic errors and provides 100% coverage.

Black box Testing of Estimator

    /**
     * Estimate the total cost of a job. The base cost is 0, requesting a fast
     * job adds $5 to the cost, requesting a good job adds $10 to the cost.
     * 
     * @param fast Does the customer want the job done fast?
     * @param good Does the customer want the job done correctly?
     * @return Estimate of the job cost in dollars.
     */
    public static int totalCost(boolean fast, boolean good) {
Input Expected Result
fast=false, good=false 0
fast=true, good=false 5
fast=false, good=true 10
fast=true, good=false 15

Test-Driven Development

Regression Testing

If time… One More Quiz

Open up a copy of LetterTest.java from PA1.

Take a minute to read over the tests then answer the following questions (privately) in the chat:

  1. Indicate places in these tests (if any) where our tests don’t follow the advice from today’s lecture.