一、单元测试的应用
Java编程中,单元测试可以保证我们的类中的方法调用不是错误的,给后面的调用提供安全保障;
二、单元测试中的注解使用:
@ Test:表示用其注释
公共方法可以作为一个测试用例,需要用public修饰void类型返回;
@Before: 用其注释的方法必须在类中的每一个测试之前执行,以便执行测试某些必要的先决条件;
@ After:用其注释的方法在执行每个测试后执行,如执行变量的重置,删除等操作。
@BeforeClass:用其注释的
静态方法必须执行一次,而且在类的所有测试之前,发生这种情况一般是测试计算共享配置方法,如链接数据库等;
@ AfterClas:当㔿执行的所有测试在JUnit测试用例类后执行,用次注解的
静态方法可以使用以清理建立方法,如断开数据库链接等。
三、单元测试示例:
实体类:
@Entity @Table(name = "funding_info_map", uniqueConstraints = @UniqueConstraint(columnNames = "id")) @Getter @Setter @ToString public class FundingInfoMap implements Serializable { private static final long serialVersionUID = -1L; @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "occupation") private Long occupation ; @Column(name = "education") private Long education ; @Column(name = "monthly_income") private Long monthlyIncomeRange ; @Column(name = "marital_status") private Long maritalStatus ; public boolean isItemDisplay(Long itemCode){ if(itemCode==0){ return false; } return true; }
public Map<String,Long> getFinaShowMap(FundingInfoMap fundingInfoMap){ Map<String,Long> finaMap = new HashMap<String,Long>(); finaMap.put(Constants.occupationEnumInfo.occupation,fundingInfoMap.getOccupation()); finaMap.put(Constants.educationEnumInfo.education,fundingInfoMap.getEducation()); finaMap.put(Constants.monthlyIncomeRangeEnumInfo.monthlyIncomeRange,fundingInfoMap.getMonthlyIncomeRange()); return finaMap; } }
测试类:
import org.junit.*; import java.util.Map; public class TestFundingInfoMap { FundingInfoMap fundingInfoMap; @BeforeClass public static void initFundingInfo() { System.out.println("测试开始,@BeforeClass"); } @Before public void initFund() { fundingInfoMap = new FundingInfoMap(); fundingInfoMap.setEducation(2L); fundingInfoMap.setOccupation(1L); System.out.println("初始化对象@Before"); } @Test public void testIsDisplay() { boolean isDis = fundingInfoMap.isItemDisplay(2L); System.out.println("是否可以显示的:" + isDis); } @Test public void testGetFinaShowMap() { Map<String, Long> addressMap = fundingInfoMap.getFinaShowMap(fundingInfoMap); System.out.println("addressMap为:" + addressMap); } @After public void testAfter() { System.out.println("Test后的after @After"); } @AfterClass public static void endFundingInfo() { System.out.println("测试结束,@AfterClass"); } }
执行结果: