Java面试题--Junit

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pzq915981048/article/details/89011815

如何测试静态方法?

a)将private方法的访问符改为 default (因为default访问修饰符课在同一个包中访问)

b) 用反射机制 method.getDeclaredMethod()

怎么利用 JUnit 来测试一个方法的异常?

1. try…fail...catch…

@Test

public voidtestExceptionMessage() {

      try {

          new ArrayList<Object>().get(0);

          fail("Expected an IndexOutOfBoundsException to be thrown");

      } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {

          assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));

      }  

}

这种写法看上去和实现类的写法很相似,当没有异常被抛出的时候fail方法会被调用,输出测试失败的信息。

2.@Test(expected=xxx)

这种写法看上去简单了一些,但是它有一个潜在的问题:当被标记的这个测试方法中的任何一个操作抛出了相应的异常时,这个测试就会通过。这就意味着有可能抛出异常的地方并不是我们期望的那个操作。虽然这种情况可以在写test case的时候人为的避免,但是还是有更好的方法来测试异常抛出。

3.ExpectedException Rule

@Rule

public ExpectedException thrown = ExpectedException.none();



@Test

public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {

        List<Object> list = new ArrayList<Object>();

        thrown.expect(IndexOutOfBoundsException.class);

        thrown.expectMessage("Index: 0, Size: 0");

        list.get(0); // execution will never get past this line  

}

这种方法除了可以指定期望抛出的异常类型之外还可以指定在抛出异常时希望同时给出的异常信息。它需要在测试之前使用Rule标记来指定一个ExpectedException,并在测试相应操作之前指定期望的Exception类型(如IndexOutOfBoundException.class)

  

junit常见注解含义以及执行顺序?

@Before:初始化方法   对于每一个测试方法都要执行一次(注意与BeforeClass区别,后者是对于所有方法执行一次)

@After:释放资源  对于每一个测试方法都要执行一次(注意与AfterClass区别,后者是对于所有方法执行一次)

@Test:测试方法,在这里可以测试期望异常和超时时间 

@Test(expected=ArithmeticException.class)检查被测方法是否抛出ArithmeticException异常 

@Ignore:忽略的测试方法 

@BeforeClass:针对所有测试,只执行一次,且必须为static void 

@AfterClass:针对所有测试,只执行一次,且必须为static void 

一个JUnit4的单元测试用例执行顺序为: 

@BeforeClass -> @Before -> @Test -> @After -> @AfterClass; 

每一个测试方法的调用顺序为: 

@Before -> @Test -> @After; 

猜你喜欢

转载自blog.csdn.net/pzq915981048/article/details/89011815
今日推荐