四、Junit参数化设置

package com.myz.util;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class JunitParameterTest {
    
    /**
     * 1.更改默认的运行器为@RunWith(Parameterized.class)
     * 2.声明变量来存放预期值和结果值
     * 3.声明一个返回值为collection的公共静态方法,并使用@Parameters进行修饰
     * 4.为测试类声明一个带参数的公共构造函数,并在其中为之声明变量赋值
     */
    
    int expected=0;
    int input1=0;
    int input2=0;
    
    @Parameters
    public static Collection<Object[]> t(){//保存参数
        return Arrays.asList(new Object[][]{
            {3,1,2},
            {4,2,2}
        });
    }

    public JunitParameterTest(int expected, int input1, int input2) {
        this.expected = expected;
        this.input1 = input1;
        this.input2 = input2;
    }
    
    @Test
    public void testAdd(){//将参数传入,测试
        assertEquals(expected,new Calculate().add(input1, input2));
    }
}

 

转载于:https://www.cnblogs.com/myz666/p/8465471.html

JUnit参数化设置JUnit框架中的一个功能,它允许我们在运行测试方法时使用不同的参数进行多次测试。通过参数化设置,我们可以更方便地编写和管理测试用例,减少代码的冗余。 在JUnit 4及以上版本中,参数化设置可以通过使用`@Parameterized`注解和`@RunWith(Parameterized.class)`注解来实现。具体步骤如下: 1. 创建一个测试类,并在类上添加`@RunWith(Parameterized.class)`注解,指定运行器为`Parameterized`。 2. 在测试类中定义私有的实例变量,用于存储测试方法的参数。 3. 创建一个公共的静态方法,用于生成测试数据。该方法需要使用`@Parameters`注解进行标记,并返回一个由测试数据组成的集合。 4. 在测试类的构造方法中,接收测试数据作为参数,并将其赋值给实例变量。 5. 编写测试方法,使用实例变量作为参数进行测试。 下面是一个示例代码: ```java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class ParameterizedTest { private int input; private int expected; public ParameterizedTest(int input, int expected) { this.input = input; this.expected = expected; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {1, 2}, {2, 4}, {3, 6} }); } @Test public void testMultiply() { MyClass myClass = new MyClass(); int result = myClass.multiply(input); assertEquals(expected, result); } } ``` 在上面的示例中,我们使用`@RunWith(Parameterized.class)`注解指定了运行器为`Parameterized`,并在`data()`方法中返回了一个包含测试数据的集合。在测试方法`testMultiply()`中,我们使用了实例变量`input`作为参数进行测试,并使用`assertEquals()`方法进行断言。 这样,当我们运行该测试类时,JUnit会自动根据`data()`方法返回的测试数据集合,依次执行测试方法,并将每组测试数据作为参数传入。 希望以上解答能够帮助到你!如果你还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值