What is unit testing
I wrote a class and wanted to use it for others. Will there be any bugs? what to do? Test it.
Is it good to use the main method to test? not good!
Can't run together!
In most cases, human observation output is required to determine whether it is correct.
Why do unit tests
Reuse tests to cope with future implementation changes.
Improve morale and know clearly that my stuff is OK.
JUnit4 HelloWorld
Need to import JUnit and hamcrest packages
new project
Create a class and create a testcase
assertThat
Using hamcrest's matching method
Give up old assertions and use hamcrest assertions
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 test failure
Error means that there is an error in the test program itself
JUnit4 Annotation
@Test: Test method
a) (expected=XXException.class)
b) (timeout=xxx)
2.@Ignore: Ignored test method
3.@Before: Run before each test method
4.@After: Run after each test method
5.@BeforeClass: Run before all tests start
6.@AfterClass: Run after all tests are finished
Run multiple tests
Notice
Abide by the agreement, such as:
a) Class placed in test package
b) Class name ends with XXXTest
c) Methods are named with testMethod
Other frameworks
TestNG
The above must-read article for getting started with JUnit unit tests is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.