junit测试
导入junit-4.8.2.jar
package test; import org.junit.*; import java.util.Optional; public class ATest { /** * 1、@BeforeClass修饰的方法会在所有方法被调用前被执行 * 而且该方法是静态的,所有当测试类被加载后接着就会运行它 * 而且在内存中它只会存在一份实例,它比较适合加载配置文件 * 2、@AfterClass所修饰的方法通常用来对资源的清理,如关闭数据库的连接 * 3、@Before和@After会在每个测试方法的前后各执行一次 */ @BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("this is @BeforeClass ..."); } @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("this is @AfterClass ..."); } @Before public void setUp() throws Exception { System.out.println("this is @Before ..."); } @After public void tearDown() throws Exception { System.out.println("this is @After ..."); } @Test public void test1() { System.out.println("this is test1 ..."); String userName = "Green"; Optional<String> userNameOpt = Optional.of(userName); Assert.assertEquals(userName, userNameOpt.get()); } @Test public void test2() { System.out.println("this is test2 ..."); ATest aTest = new ATest(); Integer value1 = null; Integer value2 = new Integer(10); // Optional.ofNullable - 允许传递为 null 参数 Optional<Integer> a = Optional.ofNullable(value1); // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException Optional<Integer> b = Optional.of(value2); System.out.println(aTest.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b){ // Optional.isPresent - 判断值是否存在 System.out.println("第一个参数值存在: " + a.isPresent()); System.out.println("第二个参数值存在: " + b.isPresent()); //Integer value = a.get(); //值不存在所以会报错java.util.NoSuchElementException: No value present // Optional.orElse - 如果值存在,返回它,否则返回默认值 Integer value1 = a.orElse(new Integer(1)); //Optional.get - 获取值,值需要存在 Integer value2 = b.get(); return value1 + value2; } }
执行结果
this is @BeforeClass ... this is @Before ... this is test1 ... this is @After ... this is @Before ... this is test2 ... 第一个参数值存在: false 第二个参数值存在: true 11 this is @After ... this is @AfterClass ...

浙公网安备 33010602011771号