Getting started with JUnit unit testing is a must read

  • 2020-11-18 06:14:56
  • OfStack

What is a unit test

If I write a class and I want to give it to someone else, is there an bug? How to do? Let's test 1.

How about using the main method? Not good!

Cannot run 1!

In most cases you need to look at the output manually to make sure it's correct

Why unit testing

Reuse tests to cope with future implementation changes.

It's ok to raise morale and know exactly what I have.

JUnit4 HelloWorld

You need to import the JUnit and hamcrest packages

new project
Establish a class
Establish testcase
assertThat
Use hamcrest's matching method

Discard the old assertion and use the hamcrest assertion

a)

assertThat( n, allOf( greaterThan(1), lessThan(15) ) );
assertThat( n, anyOf( greaterThan(16), lessThan(8) ) );
assertThat( n, anything() );
assertThat( str, is( "bjsxt" ) );
assertThat( str, not( "bjxxt" ) );

b)

assertThat( str, containsString( "bjsxt" ) );
assertThat( str, endsWith("bjsxt" ) );
assertThat( str, startsWith( "bjsxt" ) );
assertThat( n, equalTo( nExpected ) );
assertThat( str, equalToIgnoringCase( "bjsxt" ) );
assertThat( str, equalToIgnoringWhiteSpace( "bjsxt" ) );

c)

assertThat( d, closeTo( 3.0, 0.3 ) );
assertThat( d, greaterThan(3.0) );
assertThat( d, lessThan (10.0) );
assertThat( d, greaterThanOrEqualTo (5.0) );
assertThat( d, lessThanOrEqualTo (16.0) );

d)

assertThat( map, hasEntry( "bjsxt", "bjsxt" ) );
assertThat( iterable, hasItem ( "bjsxt" ) );
assertThat( map, hasKey ( "bjsxt" ) );
assertThat( map, hasValue ( "bjsxt" ) );

Failure and Error

Failure means the test failed
Error means the test program itself is faulty

JUnit4 Annotation

Test: Test method

a) (expected=XXException.class)

b) (timeout=xxx)

Ignore: Ignored test methods

3. @Before: Run before each test method

After: Run after each test method

BeforeClass: Run all tests before they start

AfterClass: Run after all tests are done

Run multiple tests

Pay attention to

Abide by the agreement, such as:

The a) class is placed in the test package

b) class names end with XXXTest

c) method named after testMethod

Other frameworks

TestNG


Related articles: