How to test static methods ?

a) take private Method to default ( because default Access modifiers are accessed in the same package )

b) Using reflection mechanism method.getDeclaredMethod()

 

How to use it JUnit To test the exception of a method ?

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"));       }   }
It looks very similar to the implementation class , When no exception is thrown fail Method will be called , Output test failure information .

 

2.@Test(expected=xxx)

 

This way of writing seems simpler , But it has a potential problem : When any operation in the marked test method throws an exception , This test will pass . This means that the place where it is possible to throw an exception is not the operation we expect . Although this situation can be written in test
case It's a man-made avoidance , But there is a better way to test exception throw .

 

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   }

This method can not only specify the type of exception expected to be thrown, but also specify the exception information expected to be given at the same time when an exception is thrown . It needs to be used before testing Rule Tag to specify a ExpectedException, And specify the expected Exception type ( as IndexOutOfBoundException.class)

  

 

junit Common annotation meaning and execution sequence ?

 

@Before: Initialization method    Each test method is executed once ( Attention and BeforeClass difference , The latter is executed once for all methods )

@After: Release resources   Each test method is executed once ( Attention and AfterClass difference , The latter is executed once for all methods )

@Test: test method , Here you can test the expected exception and timeout  

@Test(expected=ArithmeticException.class) Check whether the method under test is thrown ArithmeticException abnormal  

@Ignore: Ignored test methods  

@BeforeClass: For all tests , Only once , And must be static void 

@AfterClass: For all tests , Only once , And must be static void 

One JUnit4 The execution order of the unit test cases is : 

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

The calling order of each test method is : 

@Before -> @Test -> @After; 

 

Technology