Junit4 Parameterized参数化和自动注解一起使用

1.@BeforeClass 和 @AfterClass 对于那些比较“昂贵”的资源的分配或者释放来说是很有效的,因为 他们只会在类中被执行一次。相比之下对于那些需要在每次运行之前都要初始化或者在运行之后都需要被清理的资源来说使用@Before和@After同样是一个比较明智的选择。
2.@BeforeClass 和 @AfterClass必须声明为public static,而@Before和@After必须声明为public 并且非static。
3.Parameterized参数化和自动注解一起使用例子

注:TestContextManager这个类的效果与@RunWith(SpringJUnit4ClassRunner.class)一样自动注解。

JUnit参数化测试的五个步骤:
(1)为准备使用参数化测试的测试类指定特殊的运行器 org.junit.runners.Parameterized。
(2)为测试类 声明几个变量,分别用于存放期望值和测试所用数据。
(3)为测试类声明一个 带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。
(4)为测试类声明一个使用注解 org.junit.runners.Parameterized. Parameters 修饰的,返回值为 java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。
(5)编写 测试方法,使用定义的变量作为参数进行测试。



import java.util.Arrays;  
import java.util.Collection;  
  
import org.junit.Before;
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.junit.runners.Parameterized;  
import org.junit.runners.Parameterized.Parameters;  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;


  
//(1)步骤一:测试类指定特殊的运行器org.junit.runners.Parameterized  
@RunWith(Parameterized.class)
@ContextConfiguration(locations = { "classpath:applicationContext-*.xml" })
public class SpringJunit4Parameterized{  
    
	@Autowired
    private XXService xxService ;  
  
	private TestContextManager testContextManager ;
	
    //每次运行都会执行  与 @BeforeClass的区别
    @Before  
    public void setUp(){  
        //自动注解与@RunWith(SpringJUnit4ClassRunner.class) 效果一样
    	testContextManager = new TestContextManager(getClass()) ;
    	try {
			testContextManager.prepareTestInstance(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }  
  
    // (2)步骤二:为测试类声明变量,分别用于存放期望值和测试所用数据。此处我只放了测试所有数据,没放期望值。  
    private String eventid;  
  
    // (3)步骤三:为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。  
    public SpringJunit4Parameterized(String eventid) throws Exception{  
        this.eventid = eventid;  
    }  
  
    // (4)步骤四:为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,返回值为  
    // java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。
    @SuppressWarnings("all")
    @Parameters  
    public static Collection eventidData() {  
  
    	return Arrays.asList(new Object[][]{  
                {"BBB1"}  
        });    
  
    }  
  
    // (5)步骤五:编写测试方法,使用定义的变量作为参数进行测试。  
    @Test  
    public void testFindByName() {  
        System.out.println("**************");  
        XXBO xx= this.xxService.getxxByID(eventid);  
        System.out.println(xx.getEventid());  
    }  
}  


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值