开发者

Junit test methods

开发者 https://www.devze.com 2023-01-11 04:26 出处:网络
What are the most oftenly used test methods I sh开发者_运维百科ould 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 somet

What are the most oftenly used test methods I sh开发者_运维百科ould 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() and tearDown(), they are called before and after each 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 and @After annotations (equivalent to what setUp() and tearDown() are for).

0

精彩评论

暂无评论...
验证码 换一张
取 消