经典JUnit测试

xiaoxiao2021-02-28  69

经典JUnit测试 @BeforeClass:针对所有测试,只执行一次,且必须为static void @Before:初始化方法 @Test:测试方法,在这里可以测试期望异常和超时时间 @After:释放资源 @AfterClass:针对所有测试,只执行一次,且必须为static void @Ignore:忽略的测试方法 一个单元测试用例执行顺序为: @BeforeClass –> @Before –> @Test –> @After –> @AfterClass 每一个测试方法的调用顺序为: @Before –> @Test –> @After

Demo1:   SpringTest import java.util.Date;

import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

private static ApplicationContext context=null; @BeforeClass public static void setUpBeforeClass() throws Exception { context=new ClassPathXmlApplicationContext("applicationContext.xml"); }

/* 测试Bean 加载是否成功 applicationContext {< bean id=”date” class=”java.util.Date” />} */

@Test public void test() { Date date=(Date) context.getBean("date"); System.out.println(date); }

}

Demo2:   TaskTest2

package com.cxkh.pjgl.dao.impl; public class TaskTest2 {

public int add(int a, int b){ return a + b; } public int subtract(int a, int b){ return a - b; } public int multiply(int a, int b) { return a * b; } public int divide(int a, int b) throws Exception{ if (0 == b) { throw new Exception("除数不能为0"); } return a / b; } }

Demo3:   ParameterTest import static org.junit.Assert.assertEquals;

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 ParameterTest{

/** * 更改默认的测试运行器为RunWith(Parameterized.class) * 更改变量俩存放预期值和结果值 * 声明一个返回值为Collection的公共静态方法,并使用@Paeameters进行修饰 * 为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值 */ int expected =8; int input1 =1; int input2 =7; @Parameters public static Collection<Object []> t() { return Arrays.asList(new Object[][]{ {3,1,2},{4,2,2} }); } public ParameterTest(int expected,int input1,int input2){ this.expected=expected; this.input1=input1; this.input2=input2; } @Test public void testAdd() { // TODO Auto-generated method stub assertEquals(expected,new TaskTest2().add(input1, input2)); }

}

转载请注明原文地址: https://www.6miu.com/read-52224.html

最新回复(0)