minte9
LearnRemember



Test Case

A test case provides an example of expected behavior.
T 
/**
 * Test Case - AssertEquals Example
 * 
 * AAA (Arrange, Act, Assert)
 */

package com.minte9.junit.test_case;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class CaseTest {

    @Test public void mytest() { // Look Here
        
        // Arange
        Squares squares = new Squares();
        squares.add(3); // 9
        squares.add(5); // 25

        // Act
        int actual = squares.average();  // 9 + 25 = 34
        int expected = 17;

        // Assert
        assertEquals(actual, expected); // passed
    }
}

class Squares {

    private List<Integer> squares = new ArrayList<>();

    public void add(int x) {
        squares.add(x * x); 
    }

    public int average() { 
        int total = squares.stream().mapToInt(Integer::intValue).sum();
        return total / squares.size(); 
    }
}
A test case example using generic types.
T 
/**
 * Test Cases - with Generic type params
 */

package com.minte9.junit.test_case;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class GenericsTest {

    @Test public void integers() {
        
        MyList<Integer> numbers = new MyList<>();
        numbers.add(3);
        numbers.add(5);

        assertEquals(numbers.sum(), 8); // passed
    }

    @Test public void doubles() {
        
        MyList<Double> numbers = new MyList<>();
        numbers.add(3.0);
        numbers.add(5.0);

        assertEquals(numbers.sum(), 8);        // passed
        assertNotEquals(numbers.sum(), "8.0"); // passed
    }
}

class MyList<T extends Number> {

    private List<T> items = new ArrayList<>();

    public void add(T t) {
        items.add(t); 
    }

    public int sum() { 
        return items.stream()
                    .mapToInt(Number::intValue)
                    .sum();
    }
}
A test case example using lambdas and functional interface
T 
/**
 * Test Case - AssertEquals Lambdas Example
 */

package com.minte9.junit.test_case;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class LambdasTest {
    
    @Test public void mytest() {

        SQ squares = new SQ();
        squares.add(() -> 3 * 3); // Look Here
        squares.add(() -> 5 * 5);

        assertEquals(squares.average(), 17); // passed
    }
}

class SQ {

    private List<Square> squares = new ArrayList<>(); // Look Here

    public void add(Square s) { 
        squares.add(s); 
    }

    public int average() {
        int total = squares.stream().mapToInt(Square::get).sum();
        return total / squares.size();
    }
}

@FunctionalInterface interface Square { // Look Here
    int get(); 
}



  Last update: 308 days ago