Bazı test caseler için exception verebilir ve verdiğinde de bunun başarılı bir sonuç olmasını isteyebiliriz; çümkü çalışmasını istediğimiz şartlar sadece olumlu şartlar olmayabilir. Hemen kısa bir örneğe göz atalım.
package com.farukbozan.jfr.util; public class ExceptionClass {public double div(double value1, double value2) throws ArithmeticException { if (value2 == 0) { throw new ArithmeticException(); } return (value1 / value2); }} |
Çok basit bir şekilde bölme işlemi için bölen 0 geldiğinde ArithmeticException veriyoruz. Şimdi de test sınıfına bakalım.
@Test public void testDiv() { double value1 = 10.0; double value2 = 2.0; ExceptionClass instance = new ExceptionClass(); double expResult = 5.0; double result = instance.div(value1, value2); assertEquals(expResult, result, 0.0); }@Test(expected = ArithmeticException.class) public void testDivArithmeticException() { double value1 = 10.0; double value2 = 0.0; ExceptionClass instance = new ExceptionClass(); double expResult = 10.0; double result = instance.div(value1, value2); assertEquals(expResult, result, 0.0); } |
İlk testimiz olağan değerler ile çalışıp sonuç döndürüyor; fakat ikinci test case için bölen 0 olduğundan ArithmeticException alıyoruz.
@Test(expected = ArithmeticException.class)
ifadesi testimizin yine de başarılı, geçerli olmasını sağlıyor.
Bol Java’ lı günler dileğiyle… 😀
No responses yet