public class SimpleTest { public int topla(int a, int b){ return a+b; } }Kod sadece verilen iki sayıyı toplamaktadır. topla method'unun doğru çalıştığını test etmek için aşağıdaki gibi bir test sınıfı yazılabilir:
import org.junit.*; import static org.junit.Assert.*; public class Tester { @Test public void testTopla(){ SimpleTest simple=new SimpleTest(); int c=simple.topla(1,2); assertEquals(3, c); } }@Test annotation'ı bir fonksiyonun test kodu içerdiğini belirtir. Eclipse vb.. bir çok editor bu ifadeyi doğrudan çalıştırmanızı sağlayacak desteği bulunmkatadır.
public class SimpleTest { public int topla(int a, int b){ return a+b; } public int carp(int a, int b){ return a*b; } }Bu sınıf içindeki topla ve carp method'larını test eden sınıf aşağıdaki gibi yazılabilir:
import org.junit.*; import static org.junit.Assert.*; public class Tester { SimpleTest simple=null; @Before public void setUp(){ simple=new SimpleTest(); } @After public void tearDown(){ simple=null; } @Test public void testTopla(){ int c=simple.topla(1,2); assertEquals(3, c); } @Test public void testCarp(){ int c=simple.carp(1,2); assertEquals(2, c); } }Yukarıdaki örnekte, SimpleTest nesnesi setUp içinde yapılmaktadır. Bu şekilde her test öncesi nesne yaratılır ve test sonrası nesne null haline getirilir
@Test(expected = IllegalArgumentException.class) public void negatifTest(){ Simple.isle(3,-1); }Simple sınıfındaki isle methodu , IllegalArgumentException fırlatmalıdır. Eğer IllegalArgumentException oluşmaz ise test başarısız olmuştur
import org.junit.runner.*; import org.junit.runners.*; @RunWith(Suite.class) @Suite.SuiteClasses({ Test1.class, Test2.class, Test3.class, Test4.class }) public class SimpleTestSuite { // bu sınıfın dolu olmasına gerek yoktur }Test suite 4 test sınıfından oluşmaktadır ve test suite çalıştırıldığında testler sırasıyla çalıştırılacaktır
public class Toplar { public int topla(int a, int b){ return a+b; } } public class Carpar { public int carp(int a, int b){ return a*b; } }Yukarıdaki iki sınıf için ayrı aşağıdaki gibi iki test sınıfı yapılmıştır:
import static org.junit.Assert.*; import org.junit.*; public class ToplaTest { Toplar simple; @Before public void setUp(){ simple=new Toplar(); } @Test public void testTopla(){ int c=simple.topla(1,2); assertEquals(3, c); } } import static org.junit.Assert.*; import org.junit.*; public class CarpTest { Carpar simple; @Before public void setUp(){ simple=new Carpar(); } @Test public void testCarp(){ int c=simple.carp(1,2); assertEquals(2, c); } }Yukarıdaki iki testi aynı anda çalıştırabilmek için aşağıdaki gibi bir suite yaratılabilir:
import org.junit.runner.*; import org.junit.runners.*; @RunWith(Suite.class) @Suite.SuiteClasses({ ToplaTest.class, CarpTest.class }) public class IslemSuit { }Yukarıdaki suit, ToplaTest ve CarpTest sınıflarını içermektedir. IslemSuit çalıştırılırsa önce ToplaTest , ardından da CarpTest sınıfları çalışacaktır
public class Toplar { public int topla(int a, int b){ return a+b; } }Toplama işlemi sadece bir kere değil, birden fazla sayıda tekrarlanabilir. Bunun için aşağıdaki gibi bir test sınıfı yazılabilir:
import static org.junit.Assert.*; import java.util.*; import org.junit.*; import org.junit.runner.*; import org.junit.runners.*; import org.junit.runners.Parameterized.*; @RunWith(value = Parameterized.class) public class ToplaTest { private int number1; private int number2; private int expected; public ToplaTest(int number1, int number2, int expected) { this.number1=number1; this.number2=number2; this.expected=expected; } @Parameters(name = "{index}: topla({0}+{1})={2}") public static IterableHer test için gerekli olan parametreler test sınıfın kurucusunda verilmektedir. Toplama örneğinde iki sayı ve toplama sonucu beklediğimiz sayı değerleri bulunmaktadır. Dikkat edilirse @Test ile belirtilen fonksiyon, number1, number2 ve expected şeklinde sınıf değişkenlerini kullanmaktadır. @Parameters ile kullanılacak farklı parametre örnekleri , bir Iterable
@Test public void windowsTest() { assumeTrue(System.getProperty("os.name").toLowerCase().contains("win")); // test kesilir, kosul gerceklesmedi }
public class Toplar { public int topla(int a, int b){ return a+b; } }Bu sınıfdaki topla methodu için Theory sınıfı aşağıdaki gibidir:
import org.junit.experimental.theories.*; import org.junit.runner.*; import static org.junit.Assert.*; @RunWith(Theories.class) public class TheoryTest { @DataPoints public static int[] first = new int[] {1, 2}; @DataPoints public static int[] second = new int[] {3, 4}; @Theory public void testTopla(int a, int b) { System.out.println(a+"+"+b); assertEquals(a+b, (new Toplar()).topla(a, b)); } }DataPoints ile kullanılabilecek veriler verilmektedir. Verilen iki sayının + ile toplaı ile toplam fonksiyonudan gelen değerlerin tutması gerekiyor. Test çalıştırıldığında tüm olasılıklar ekrana basılmıştır:
@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ExternalSubscriptionManageTest { @Test public void test2(){..} @Test public void test3(){..} @Test public void test1(){..} }Yukarıdaki örnekte method isimlerine göre test method'ları sırayla çağrılmaktadır. Önce test1 , sonra test2 ve en son test3 çalıştırılacaktır
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.4.0-M1</version> <scope>test</scope> </dependency>Maven kullanmıyorsanız gerekli jar'ları eklemeniz gerekir. 5.4 versiyonu henüz geliştirme aşamasındadır. Bir önceki versiyon da kullanılabilir. Test edilecek aşağıdaki gibi bir sınıf yapalım:
public class Hello { public static String hello(String name) { return "hello "+name; } }Test kodu aşağıdaki gibidir:
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class HelloTest { @Test public void helloTest() { String result=Hello.hello("test"); assertEquals("hello test", result); } }Eğer dönen metin "hello test" ise sonuç test başarılı olacaktır.
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.4.0-M1</version> <scope>test</scope> </dependency> <dependency> <groupId>io.github.glytching</groupId> <artifactId>junit-extensions</artifactId> <version>2.3.0</version> <scope>test</scope> </dependency>Öncelikle test edilecek bir sınıf yazalım. Bu sınıf bir properties dosyasını yükleyen bir sınıf olsun:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertiesLoader { private Properties properties=null; public void load(String path) throws FileNotFoundException, IOException { properties=new Properties(); try(InputStream is=new FileInputStream(path)){ properties.load(is); } } public String getProperty(String key) { return properties.getProperty(key); } }Bu sınıfı test etmek için TemporaryFolderExtension'ı kullanan bir test sınıfı aşağıdaki gibi yaratılabilir:
import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.github.glytching.junit.extension.folder.TemporaryFolder; import io.github.glytching.junit.extension.folder.TemporaryFolderExtension; @ExtendWith(TemporaryFolderExtension.class) public class PropertiesLoaderTest { private static File file; @BeforeAll public static void prepare(TemporaryFolder givenTemporaryFolder) throws IOException { file = givenTemporaryFolder.createFile("test.properties"); Properties properties=new Properties(); properties.put("test", "testvalue"); try(OutputStream os =new FileOutputStream(file)){ properties.store(os,"test properties"); } } @Test @ExtendWith(TemporaryFolderExtension.class) public void loadTest() throws IOException { PropertiesLoader loader=new PropertiesLoader(); loader.load(file.getAbsolutePath()); assertEquals("testvalue", loader.getProperty("test")); } }Sınıfın en üstünde @ExtendWith(TemporaryFolderExtension.class) ile TemporaryFolderExtension'ı kullanacağımız belirtiyoruz. @BeforeAll ile tanımlanan yöntem ile TemporaryFolder'ı alıyoruz ve bir properties dosyasını yaratıyoruz. loadTest() yönteminde ise asıl test edeceğimiz PropertiesLoader sınıfını yaratıyoruz ve verilen path'deki properties dosyasını yükletiyoruz. Eğer test değeri testvalue ise PropertiesLoader başarılı bir şekilde çalışmış demektir.
@Test public void createFileTest(@TempDir Path tempDir) { String testFilePath=tempDir.toString()+File.separator+"test.txt"; try { Files.createFile(Paths.get(testFilePath)); } catch (IOException e) { fail(e); } //... }
@RepeatedTest(100) public void testRouletteWheelSelector() { int[] values=new int[]{0,100}; int index = RouletteWheelSelector.select(values); assertEquals(1, index); }Bu test 100 kere tekrarlandığında hep başarılı olmalıdır. Çünkü ile değer 0 olasılıktır ve hep ikinci seçilecektir.
static int index1Count=0; static int index2Count=0; @BeforeAll public static void init() { index1Count=0; index2Count=0; } @RepeatedTest(10000) public void testRouletteWheelSelector50Percent() { int[] values=new int[]{50,50}; int index = RouletteWheelSelector.select(values); if(index==0) { index1Count++; }if(index==1) { index2Count++; } } @AfterAll public static void beforeAll() { System.out.println(index1Count+":"+index2Count); }