PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   11-09-2021

@Before

p19 For each test, JUnit first executes the methods marked with @Before annotation.
 
/**
 * JUnit creates a new instance for each test it runs
 * 
 * @Before methods will be exectuted before each test
 */

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

public class App {

    private Squares squares;

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

        System.out.println("Squares initialized!"); // Twice - Look Here
    }
    
    @Test public void average() {
        assertEquals(squares.average(), 17); // passed
    }

    @Test public void sum() {
        assertEquals(squares.sum(), 34); // passed
    }
}

class Squares {

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

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

    public int average() { 
        return sum() / squares.size(); 
    }

    public int sum() { 
        return squares.stream().mapToInt(Integer::intValue).sum();
    }
}
... 31 lines
 
Static method @BeforeClass is executed once before all tests.
 
/**
 * JUnit creates a new instance for each test it runs
 * 
 * @BeforeClass is executed once before all tests
 */

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

public class App {

    private static Squares squares;

    @BeforeClass static public void executedBeforeOnce() { // Look Here
        
        squares = new Squares();
        squares.add(3); // 9
        squares.add(5); // 25

        System.out.println("Squares initialized!"); // Once - Look Here
    }
    
    @Test public void average() {
        assertEquals(squares.average(), 17); // passed
    }

    @Test public void sum() {
        assertEquals(squares.sum(), 34); // passed
    }
}

class Squares {

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

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

    public int average() { 
        return sum() / squares.size(); 
    }

    public int sum() { 
        return squares.stream().mapToInt(Integer::intValue).sum();
    }
}
... 31 lines
 
p43 An @After method runs after every test method.
 
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class App {
    
    @Before public void a() {
        // game init
    }

    @Test public void b() {
        // game start
    }

    @After public void c() {
        // close connection
    }
}

class Game {}
... 9 lines
 

Questions    
Exceptions

        A B C D E F
🔔
1/1