PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   16-08-2021

Exceptions

p31 JUnit @Test annotation supports passing an argument that specify an expected exception.
 
import org.junit.Test;

public class App {

    @Test public void a() { // Failed
        int no = 7/0;
        // no Assert
    }

    @Test(expected = ArithmeticException.class) public void b() { // Passed
        int no = 7/0;
        // no Assert
    }
}
... 5 lines
 
 
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class App {

    @Test public void a() { // Failed
        Squares squares = new Squares();
        squares.average(); // ArithmeticException: / by zero
        // no Assert
    }

    @Test(expected = ArithmeticException.class) public void b() { // Passed
        Squares squares = new Squares();
        squares.average();
        // no Assert
    }

    @Test public void c() { // Passed
        Squares squares = new Squares();
        squares.add(3); // 9
        squares.add(5); // 25
        assertEquals(squares.average(), 17);
    }
}

class Squares {

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

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

    public int average() throws ArithmeticException {
        int total = squares.stream().mapToInt(Integer::intValue).sum();
        return total / squares.size();
    }
}
... 26 lines
 
Test App exception when no args are provided.
 
import org.junit.Test;

public class App {

    @Test public void a() { // Failed
        Game.main(new String[] {}); // ArrayIndexOutOfBoundsException
        // no Assert
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class) public void b() {
        Game.main(new String[] {}); // Passed
        // no Assert
    }

    @Test public void c() {
        Game.main(new String[] { "run" }); // Passed
        // no Assert
    }
}

class Game {

    public static void main(String[] args) {
        try {
            String action = args[0];
        } catch(ArrayIndexOutOfBoundsException e) {}
    }
}
... 16 lines
 

Questions    
Spring Project

        A B C D E F
🔔
1/1