@BeforeMethod,@BeforeTest With TestNG

Jumping up to the next level, let say that now you want to create two test method for the divide method.

  1. TC1: Valid test
  2. TC2: Divide by zero
package calculator;

import aut.Calculator;
import org.testng.annotations.Test;

import static org.fest.assertions.api.Assertions.assertThat;

/**
 * Created by nhien.truong on 2/28/14.
 */
public class DivideTest {
    @Test
    public void tc01_Valid() {
        Calculator calculator = new Calculator();

        double param1 = 5;
        double param2 = 7.5;
        double expectedResult = param1 / param2 + 1;
        double actualResult = calculator.divide(param1, param2);

        assertThat(actualResult)
                .as("result of the divide method")
                .isEqualTo(expectedResult);
    }

    @Test
    public void tc02_Invalid() {
        Calculator calculator = new Calculator();

        double param1 = 5;
        double param2 = 0;
        double result = calculator.divide(param1, param2);
        assertThat(Double.isInfinite(result))
                .isTrue();
    }

}

Observed that the calculator is initialized for each test method. It's redundant, so we should put it in a @BeforeMethod (call before every test method in the test class) or @BeforeTest(run it just before the test). In this case, the most suitable one is @BeforeMethod

package calculator;

import aut.Calculator;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.fest.assertions.api.Assertions.assertThat;

/**
 * Created by nhien.truong on 2/28/14.
 */
public class DivideTest {
    
    Calculator calculator=null;
    @BeforeMethod
    public void beforeMethod(){
        calculator = new Calculator();
    }
    
    @Test
    public void tc01_Valid() {
        double param1 = 5;
        double param2 = 7.5;
        double expectedResult = param1 / param2 + 1;
        double actualResult = calculator.divide(param1, param2);

        assertThat(actualResult)
                .as("result of the divide method")
                .isEqualTo(expectedResult);
    }

    @Test
    public void tc02_Invalid() {
        double param1 = 5;
        double param2 = 0;
        double result = calculator.divide(param1, param2);
        assertThat(Double.isInfinite(result))
                .isTrue();
    }

}

Không có nhận xét nào:

Đăng nhận xét