JUnit for Android入门1

从JUnit示例开始:

package com.example.myapplication;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() {
        assertEquals(4, 2 + 2);
    }
}
  • 注解:JUnit4中,支持用注解的方式标注测试方法。
    • @Test:说明该方法是测试方法,测试方法必须是public void,可以抛出异常
    • @Ignore:忽略该测试方法。在JUnit4中,在不想运行某个测试方法使,可以加上注解。
    • @Before:它会在每个测试方法执行前都调用一次
    • @After:与@Before对应,它会在每个测试方法执行完后都调用一次
      在这里插入图片描述
      执行顺序before ->test1->after->before->test2->after
    • @BeforeClass&&AfterClass
      与@Before不同的是,@BeforeClass注解的方法只会为一个测试类执行一次,@AfterClass同理。
      注意:该注解的测试方法必须是public static void修饰的。
      示例:
    package com.example.myapplication;
    
    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    public class TestJUnitLifeCycle {
        @BeforeClass
        public static void init(){
            System.out.println("----init-----");
        }
        @Before
        public void setUp(){
            System.out.println("----setup----");
        }
        @After
        public void teardown(){
            System.out.println("-----teardown-----");
        }
        @AfterClass
        public static void finish(){
            System.out.println("-----finish----");
        }/*
        @Test
        public void addition_isCorrect() {
            assertEquals(4, 2 + 2);
        }*/
        @Test
        public void test1() {
            System.out.println("test1");
        }
        @Test
        public void test2() {
            System.out.println("test2");
        }
    }
    

运行结果:
----init-----
----setup----
test1
-----teardown-----
----setup----
test2
-----teardown-----
-----finish----

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值