三分钟学会 Java 单元测试

时间:2022-04-21
本文章向大家介绍三分钟学会 Java 单元测试,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言:

此篇文章使用 Junit 4.0, 希望给无任何单元测试经验的开发者, 能在最短的时间内, 开展单元测试的工作◦

本文: 

学习 Junit 的测试框架是件非常容易的事,只需了解下列三件事:

1)     测试方法的宣告◦

2)     Junit 的生命周期◦

3)     断言的方法◦

I.           测试方法的宣告:

测试方法的宣告需遵循下列的规则:

a)     使用 @Test 将方法宣告为测试方法◦

b)     测试方法需为 public◦以确保可被 Junit 框架所调用◦

c)     测试方法需为 void 且无参数◦以确保各测试方法的独立性◦


import org.junit.Test;
import static org.junit.Assert.assertEquals;    

public class ExampleTest {

@Test

publicvoid thisIsATestMethod(){

assertEquals(5, 2 + 3);

}

@Test

public void thisIsAnotherTestMethod() {

WorldOrder newWorldOrder = new WorldOrder();

assertFalse(newWorldOrder.isComing());

}

}

II.         Junit 的生命周期:

Junit 的生命周期有下列主要的步骤:

Step 1) Junit 框架生成测试类; public class ExampleTest; 的对象◦

Step 2) Junit 框架调用测试对象中的 @Before 方法◦ 以设定测试环境, 如:生成被测对象; DefaultController( ); 或生成测试数据对象; SampleRequest()◦

Step 3) Junit 框架调用测试对象中的任一测试方法;

public void testProcessRequest() 或 public void testAddHandler()◦

因各测试方法均为独立, 所以Junit 框架先调用那个测试方法, 并不会影响各测试方法的测试结果◦

Step 4) Junit 框架调用测试对象中的 @After 方法◦ 以清除测试环境◦    

针对下一个测试方法, Junit 重复相同的生命周期 (步骤)◦

public class ExampleTest {

@Before

public void setLocaleForTests() {

  controller = new DefaultController();

  request = new SampleRequest();

  handler = new SampleHandler();

 }

@Test

public void testProcessRequest()  {

        Response response = controller.processRequest( request );

        assertNotNull( "Must not return a null response", response );

}

@Test

 public void testAddHandler() {

        RequestHandler handler2 = controller.getHandler( request );

        assertSame( "Controller.getHandler must return the samplehandler", handler2, handler );

    }

@After

}

III.       断言的方法:

JUnit assertions

Description

assertEquals

Asserts that two objects (or primitives) are equal

assertArrayEquals

Asserts that two arrays have the same items

assertTrue

Asserts that a statement is true

assertFalse

Asserts that a statement is false

assertNull

Asserts that an object reference is null

assertNotNull

Asserts that an object reference is not null

assertSame

Asserts that two object references point to the same instance

结论:

  Junit 的框架非常的容易使用◦ 然而, 如何有效率的开发 Junit 单元测试代码, 对敏捷开发而言, 绝对不是一件容易的事◦

后续将陆续探讨这方面的议题◦