如何使用Junit

2020-06-11  本文已影响0人  Zavier_copy

1.需要在build.gradle里导入依赖库

testImplementation'junit:junit:4.12'

2.添加类注解

@RunWith(JUnit4.class)

3.以下是常用的使用方法:

@RunWith(JUnit4.class)
public class JunitTest {
    @Before
    public void initData() {
    System.out.println("初始化");
    }

    @After
    public void releaseData(){
    System.out.println("内存释放");
    }

    @Test
    public void testAssertArrayEquals() {
    byte[] expected ="trial".getBytes();
    byte[] actual ="trial".getBytes();
    System.out.println("testAssertArrayEquals");
    assertArrayEquals("failure - byte arrays not same", expected, actual);
    }

    @Test
    public void testAssertEquals() {
    assertEquals("failure - strings are not equal","text","text");
    }

    @Test
    public void testAssertFalse() {
    assertFalse("failure - should be false",false);
    }

    @Test
    public void testAssertNotNull() {
    assertNotNull("should not be null",new Object());
    }

    @Test
    public void testAssertNotSame() {
    assertNotSame("should not be same Object",new Object(),new Object());
    }

    @Test
    public void testAssertNull() {
    assertNull("should be null",null);
    }

    @Test
    public void testAssertSame() {
    Integer aNumber = Integer.valueOf(768);
    assertSame("should be same", aNumber, aNumber);
    }

    // JUnit Matchers assertThat
    @Test
    public void testAssertThatBothContainsString() {
    assertThat("albumen",both(containsString("a")).and(containsString("b")));
    }

    @Test
    public void testAssertThatHasItems() {
    assertThat(Arrays.asList("one","two","three"),hasItems("one","three"));

     }

    @Test
    public void testAssertThatEveryItemContainsString() {
    assertThat(Arrays.asList(new String[] {"fun","ban","net" }),everyItem(containsString("n")));
    }

    @Test
    public void testAssertTrue() {
    assertTrue("failure - should be true",true);
    }

     /**
     * 一般用 @Rule 注解来初始化一个对象,然后在测试方法中使用这个实例
    * 示例先初始化一个 ExpectedException 实例,然后使用 expect 方法判断抛出的异常是否是 
       IndexOutOfBoundsException */
    @Rule
    public ExpectedExceptionexception = ExpectedException.none();
    @Test
    public void testRule() {
    exception.expect(IndexOutOfBoundsException.class);
     throw new IndexOutOfBoundsException();
    }
}
上一篇下一篇

猜你喜欢

热点阅读