简体   繁体   中英

Junit test methods

What are the most oftenly used test methods I should start with in order to get familiar with unit testing? There are just a lot of them, but I guess there are some like common or something.

I meant Junit methods like AssertTrue(), etc.

There are just a few patterns to learn, with multiple implementing methods for different types and an optional initial message argument.

  • assertEquals()
  • assertTrue() and assertFalse()
  • assertNull() and assertNotNull()
  • assertSame() and assertNotSame()
  • fail()
  • assertArrayEquals()
  • assertThat()

At a minimum you'll need to learn all the patterns but the last -- these are all needed for different situations.

assertEquals is the most commonly used test method.

assertEquals( "string1", "string1" ); 
//would fail

assertEquals( expectedValue, actualValue ); 
//would pass if expectedValue.equals( actualValue )

You can also add a comment that is printed if the assertion fails:

assertEquals( "method result should be 7", 7, thing.methodThatShouldReturn7() );
//would pass if 7 == thing.methodThatShouldReturn7()

See the Assert class javadoc for more details and once you are comfortable with assertEquals, you can look at the other assert options available to you.

setUp()和tearDown(),在每个case之前和之后调用它们。

I would also recommend knowing about fail() and exception handling within JUnit. The brief suggestion is to always throw exceptions from the test method unless testing for that specific exception. Catching exceptions and failing works, but you lose quite a bit of information on reports. A good article about it is here: http://www.exubero.com/junit/antipatterns.html .

@Before和@After注释(相当于setUp()和tearDown()的用途)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM