Java
JUnit temelleri
@Test ile test yazmayı öğrenirsin.
JUnit temelleri
JUnit, Java için modern bir test çerçevesidir. JUnit 5'in güncel sürümü Jupiter olarak adlandırılır ve org.junit.jupiter.api paketinden gelir. Bir test yöntemini @Test annotation ile işaretlersin.
import org.junit.jupiter.api.Test;
class CalculatorTest {
@Test
void testAdd() {
// doğrulama
}
}
Bu annotation, yöntemin bir test olduğunu bildirir; çerçeve onu otomatik olarak çalıştırır. Test sınıfı herhangi bir sınıf olabilir, ancak adı genelde XxxTest biçimindedir. Bu yapı, kod kalıtesini güvence altına alır.
JUnit 5 mimarisi
JUnit 5 üç alt modülden oluşur: Platform testleri çalıştıran motoru, Jupiter yeni test API'lerini ve Vintage eski JUnit 4 testlerini destekler.
Platform, IDE ve derleme araçlarıyla (Maven, Gradle) bütünleşir. Jupiter, @Test, Assertions ve @BeforeEach gibi API'leri sağlar. Vintage ise geçiş döneminde eski testlerin çalışmasına izin verir. Yeni kodda yalnızca Jupiter kullanılır.
Uygulama Calculator sınıfı ve testini yaz
Bir Calculator sınıfı tanımla; add(int a, int b) yöntemi iki sayıyı toplasın. CalculatorTest sınıfında @Test ile işaretli testAdd yöntemi yaz; assertEquals(5, c.add(2, 3)) ile doğrula. Bir main metodu ekle ve add(2, 3) sonucunu System.out.println ile yazdır.
Örnek çözümü göster
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
int add(int a, int b) {
return a + b;
}
}
class CalculatorTest {
@Test
void testAdd() {
Calculator c = new Calculator();
assertEquals(5, c.add(2, 3));
}
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3));
}
}
Kendini test et
-
Bir test yöntemini işaretlemek için hangi annotation kullanılır?
- @TestMethod
- @Run
- @Test
- @TestCase
Cevabı göster
@Test — @Test, JUnit 5'te bir yöntemi test olarak işaretler.
-
Test yöntemini tamamla
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
____(5, result);
}
Cevabı göster
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
assertEquals(5, result);
}
-
JUnit kavramlarını eşleştir
- @Test
- Test yöntemini işaretler
- Jupiter
- Yeni test API'sini sağlar
- Platform
- Testleri çalıştıran motor
- Assertions
- Doğrulama yöntemleri
Sıradaki ders: Assertions