2. előadás
Tesztelés - Egység teszt (Unit test)
A programozó hibázik
Külsö segéd eszközök
Mi az hogy Unit?
A lehető legkisebb egység ami egy egységnek minősűl (Javaban: egy osztály vagy egy teljesen különálló metódus).
A program kicsi része jól fut e vagy sem?
Tesztek függetlenek egymástól
Mindig minden a lehető legzöldebb legyen
System Under Test (SUT) váljon el minnél jobban a tesztelő kód a tesztelt kódtól
TDD (Test Driven Development)
- Új "piros" tesztek hozzáadása
- Kód írása/fejlesztése: mindek test "zőld"
- Kód minőség fejlesztése (refactoring)
Más megközelítés
- Logging, printouts
- Debugging (breakpoints)
- Haladó megközelítés:
- naplózás (történeti visszakeresés)
- automatikus (CI/CD)
- Minden be van bizonyítva szemantikusan
Példakód
//Calculator.java
package calc;
public class Calculator{
public static int add (int num1, int num2){
return num1+num2;
}
public static double sqrt(double value){
if(value < 0.0) throw new IllegalArgumentException();
return Math.sqrt(value);
}
}
//CalculatorTest.java
package calc;
import static org.junit.jupiter.api.Assertions.assertEquals();
import static org.junit.jupiter.api.Assertions.assertAll();
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class CalculatorTest{
@Test
public void test(){
assertEquals(4, Calculator.add(2,2), "aasdasd" /*teszt leírása*/);
}
@ParameterizedTest
//@CsvSource({"123, 123"})
@CsvSource({textBlock = """
123, 123
125, 1223
-123, -123
"""})
public void test2(String input, int expected){
assertEquals(expected, input);
}
@Test
public void test3(){
assertAll(
() -> assertEquals(4, 2+632),
() -> assertEquals(5, 2+33)
);
}
@Test
public void test4(){
assertThrows(IllegalArgumentException.class,() -> { Calculator.sqrt(-5);
}
);
}
@Test
public void test5(){
assertTrue(4 == 2 + 6432);
assertFalse(4 == 2 + 6432);
fail("description");
}
@Test
public void test6(){
assertEquals("4", "4" + "");
ArrayList<String> txts = new ArrayList<>();
txts.add("4");
assertEquals(List.of("4"),txts);
//nem szokásos módon működik
int[] nums = {1,2,3};
//assertEquals(new int[] {1,2,3}, nums);
assertArrayEquals(new int[] {1,2,3}, nums);
}
}
public class NestedTest{
List<String> history;
@Test
public void firstStep(){
history = new ArrayList<>();
assertEquals(List.of(), history);
}
@Nested
class Step1 {
@BeforeEach
public void step(){
history.add("step1");
}
@Test
public void stepTwo(){
asertEquals(List.of("init", "step1"), history);
}
@Test
public void twoElems(){
asertEquals(2, history.size());
}
}
}