Thursday, January 04, 2007

Unit Testing with JUnit 4.0

JUnit 4 introduces a completely different API to the older versions. JUnit 4 uses Java 5 annotations to describe tests instead of using inheritence. It introduces more flexible initialization and cleanup, timeouts, and parameterized test cases. This post describes the new features in JUnit 4, and in the end, I show a basic example that tests the java.util.Stack class.
  1. The tests: Unlike in JUnit 3.x you don't have to extend TestCase to implement tests. A simple Java class can be used as a TestCase. The test methods have to be simply annotated with org.junit.Test annotation as shown below
    @Test
    public void emptyTest() {
    stack = new Stack<String>();
    assertTrue(stack.isEmpty());
    }
  2. Using Assert Methods: In JUnit 4 test classes do not inherit from TestCase, as a result, the Assert methods are not available to the test classes. In order to use the Assert methods, you have to use either the prefixed syntax (Assert.assertEquals()) or, use a static import for the Assert class.
    import static org.junit.Assert.*;
    Now the assert methods may be used directly as done with the previous versions of JUnit.
  3. Changes in Assert Methods: The new assertEquals methods use Autoboxing, and hence all the assertEquals(primitive, primitive) methods will be tested as assertEquals(Object, Object). This may lead to some interesting results. For example autoboxing will convert all numbers to the Integer class, so an Integer(10) may not be equal to Long(10). This has to be considered when writing tests for arithmetic methods. For example, the following Calc class and it's corresponding test CalcTest will give you an error.
    public class Calc {
    public long add(int a, int b) {
    return a+b;
    }
    }
    Calc.java
    import org.junit.Test;
    import static org.junit.Assert.assertEquals;

    public class CalcTest {
    @Test
    public void testAdd() {
    assertEquals(5, new Calc().add(2, 3));
    }
    }
    CalcTest.java
    You will end up with the following error.
    java.lang.AssertionError: expected:<5> but was:<5>
    This is due to autoboxing. By default all the integers are cast to Integer, but we were expecting long here. Hence the error. In order to overcome this problem, it is better if you type cast the first parameter in the assertEquals to the appropriate return type for the tested method as follows
    assertEquals((long)5, new Calc().add(2, 3));
    There are also a couple of methods for comparing Arrays
    public static void assertEquals(String message, Object[] expecteds, Object[] actuals);
    public static void assertEquals(Object[] expecteds, Object[] actuals);
  4. Setup and TearDown: You need not have to create setup and teardown methods for setup and teardown. The @Before, @After and @BeforeClass, @AfterClass annotations are used for implementing setup and teardown operations. The @Before and @BeforeClass methods are run before running the tests. The @After and @AfterClass methods are run after the tests are run. The only difference being that the @Before and @After can be used for multiple methods in a class, but the @BeforeClass and @AfterClass can be used only once per class.

  5. Parameterized Tests: JUnit 4 comes with another special runner: Parameterized, which allows you to run the same test with different data. For example, in the the following peice of code will imply that the tests will run four times, with the parameter "number" changed each time to the value in the array.
    @RunWith(value = Parameterized.class)
    public class StackTest {
    Stack<Integer> stack;
    private int number;

    public StackTest(int number) {
    this.number = number;
    }

    @Parameters
    public static Collection data() {
    Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
    return Arrays.asList(data);
    }
    ...
    }
    The requirement for parameterized tests is to
    • Have the annotation @RunWith for the Test Class
    • Have a public static method that returns a Collection for data. Each element of the collection must be an Array of the various paramters used for the test.
    • You will also need a public constructor that uses the parameters

  6. Test Suites: In JUnit 3.8 you had to add a suite() method to your classes, to run all tests as a suite. With JUnit 4 you use annotations instead. To run the CalculatorTest and SquareTest you write an empty class with @RunWith and @Suite annotations.
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    @RunWith(Suite.class)
    @Suite.SuiteClasses({StackTest.class})
    public class AllTests {
    }
    The "Suite" class takes SuiteClasses as argument which is a list of all the classes that can be run in the suite.

The following is a listing of the example StackTest used in the post.
package tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.Collection;
import java.util.EmptyStackException;
import java.util.Stack;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
public class StackTest {
Stack<Integer> stack;

private int number;

public StackTest(int number) {
this.number = number;
}

@Parameters
public static Collection data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}

@Before
public void noSetup() {
stack = new Stack<Integer>();
}

@After
public void noTearDown() {
stack = null;
}

@Test
public void pushTest() {
stack.push(number);
assertEquals(stack.peek(), number);

}

@Test
public void popTest() {
}

@Test(expected = EmptyStackException.class)
public void peekTest() {
stack = new Stack<Integer>();
stack.peek();
}

@Test
public void emptyTest() {
stack = new Stack<Integer>();
assertTrue(stack.isEmpty());
}

@Test
public void searchTest() {
}
}

StackTest.java

79 comments:

  1. Hi!

    Thanks for this post! It was of great help putting together a "data driven" suite for JUnit 4.0.

    One question though: in the output reports from the tests, I only get testNumber[0], testNumber[1], testNumber[2], testNumber[3]. Would it be possible to get the input parameters as names for the test in the report?

    Thanks,

    Havard

    ReplyDelete
  2. I also want to give some name various parameters. any enlightment in it.

    Also, it is not creating suite in above mentioned style.

    Regards,
    sauravkr@yahoo.com

    ReplyDelete
  3. Hi,

    I am getting line separators when i am passing strings actual & excepted.Here Strings are xml data.Please give me solution for this.

    ReplyDelete
  4. tanuja, can you give a bit more info on what you are trying to do?

    ReplyDelete
  5. Hi,
    We are doing project using axis and hibernate.In we are passing xml data as input string and the result string is also xml data.

    String will be as the xml file data.I am unable to attach my file plz tell me how can i send my class file to u to understand.

    ReplyDelete
  6. Hi,

    Thanks for the Post. It was very helpful. Can I get more details about the Parameterized tasks.

    Thanks
    maverickcertain@gmail.com

    ReplyDelete
  7. These articles are fantastic; the information you show us is interesting for everybody and is really good written. It’s just great!! Do you want to know something more? Read it...:Great investment opportunity in Costa Rica: jcondos house, costa rica beach condos, condos rentals. Visit us for more info at: http://www.jaco-bay.com/

    ReplyDelete
  8. I am a newbie in Annotations.Kindly let me know what will happen if we pass parameters to @Test like expected=Exception.class

    ReplyDelete

  9. wonderful article post. keep posting like this with us.We offer the most budget-friendly quotes on all your digital requirements. We are available to our clients when they lookout for any help or to clear queries.

    python training in bangalore

    python training in hyderabad

    python online training

    python training

    python flask training

    python flask online training

    python training in coimbatore


    ReplyDelete
  10. Am really impressed about this blog because this blog is very easy to learn and understand clearly.This blog is very useful for the college students and researchers to take a good notes in good manner,I gained many unknown information.


    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete
  11. Ah,so beautiful and wonderful post!An opportunity to read a fantastic and imaginary blogs.It gives me lots of pleasure and interest.Thanks for sharing.
    Java Training in Chennai

    Java Training in Bangalore

    Java Training in Hyderabad

    Java Training
    Java Training in Coimbatore

    ReplyDelete
  12. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Security Guard License
    Ontario Security License
    Security License Ontario
    Security License

    Thank you..

    ReplyDelete
  13. It's great to know this article. I like your content. Really it was read so interesting. Thank you very much. Fashion Bloggers In India

    ReplyDelete
  14. KGF 2 : Directed by Prashanth Neel. With Yash, Sanjay Dutt, Raveena Tandon, Prakash Raj. The blood-soaked land of Kolar Gold Fields

    ReplyDelete
  15.   Getting to the right temperature with just your body heat takes a lot longer than the other two methods. If you have time, you can opt for using your body heat to warm up your sample.  Keep it close to the skin and in the warmest parts of your body. For men, this would be near the crotch below the underwear. Women can opt for the same method or place it between the bra and the skin.  When you’re getting ready to submit the sample, make sure to verify the temperature using a stick.   Let’s get one thing straight once and for all; synthetic urine won’t work unless you follow the directions carefully. If you heat it wrong, mix it wrong, or even store it wrong, it will not work. You’ll fail your drug test if you’re not doing exactly what the directions are saying.  That being said, there could be situations where you need a tip or trick to help you out.  Synthetic urine is most often used to cheat a drug test. Most companies create whole kits to achieve this end goal. When it comes to detox shampoos, however, these clarifying additives are necessary to fully exfoliate and cleanse the scalp of toxin buildup. The best detox shampoos will include both sulfates and other hydrating-focused ingredients, like Glycerin, to help protect your scalp and hair.   This hair follicle test kit is designed specifically for those who need to pass the hair follicle drug test. We have sorted out the five best Synthetic Urine Kits for you to trust for ditching the urine drug test you will appear in

    ReplyDelete
  16. One of the best articles is this. I am looking for this article for a long time. At last, I found this on your website. Many many thanks for sharing your content.
    Bangla Calendar 2022
    Cool and beautiful stylish name

    ReplyDelete
  17. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.
    moving services near me
    commercial movers near me
    house movers ontario
    self storage company
    hiring a moving company

    ReplyDelete
  18. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.
    Permanent Makeup Near Me
    Microneedling Near Me
    Cryotherapy Near Me
    Microdermabrasion Near Me
    Waxing Near Me

    ReplyDelete
  19. Oppo launch First foldable smartphone .Oppo has teased the company’s first foldable phone.The image of the device is only shown from the spine side and we get a glimpse of the phone’s profile, revealing what appears to be a triple camera setup Article
    Click Here For website

    ReplyDelete
  20. thanks for sharing nice blog keep post https://duckcreektraining.com/

    ReplyDelete
  21. Chennai's No.1 Selenium training institute, Infycle Technologies, offers the best Selenium training in Chennai for students, freshers, and tech professionals with top-demanding technical courses such as Python, Oracle, Selenium, Java, Digital Marketing, Data Science, Cyber Security, Hadoop, iOS, and Android development with 100% hands-on training. Dial 7504633633 to get more info and a free demo.

    ReplyDelete
  22. Great Post !! Very interesting topic will bookmark your site to check if you write more about in the future. This post is really astounding one! I was delighted to read this, very much useful. Many thanks Feel free to visit my website; 온라인카지노

    ReplyDelete
  23. Hey there. I found your site by the use of Google whilst looking for a similar subject, your site came up. It looks good. I have bookmarked it in my google bookmarks to visit then. Feel free to visit my website; 안전놀이터

    ReplyDelete
  24. I'm glad that i found this type of site, after so many hours of searching of a marvelous site like yours so. Thanks a lot. Feel free to visit my website; 카지노

    ReplyDelete
  25. This is one very interesting post. I like the way you write and I will bookmark your blog to my favorites. Feel free to visit my website; 토토

    ReplyDelete
  26. Eve başka bir çocuk getirdiğinizde, köpeğiniz akıllara durgunluk veren çok sayıda yeni görüntü, ses ve kokuyla karşılaşacaktır. Bazılarını rahatsız edici bulabilir, özellikle de bir köpek olarak çocuklara enerji yatırma şansı yoksa.
    Visit our wab!
    Visit our wab!
    Visit our wab!
    Visit our wab!
    Visit our wab!

    ReplyDelete
  27. Infycle Technology, No.1 Software Training Institute in Chennai, afford best Data Science training in Chennai and also provide technical courses like Oracle, Java, Big data, AWS, Python, DevOps, Digital Marketing, Selenium Testing, etc., and we also provide the best training from the best technical trainers and after completion of training students will be able to crack the jobs on top MNC’s. for more information call 7504633633.

    ReplyDelete
  28. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

    ReplyDelete
  29. webgirls In relation to battling candidiasis, sufferers often times have their function reduce on their behalf. This is because infections can readily turn out to be persistent and continuous. With that in mind, in the following paragraphs, we will provide a wide range of some of the finest proven candida therapy and elimination ideas close to.

    ReplyDelete
  30. https://gameeffect.xyz Many people have loved the video game of baseball for a long time. There are actually followers around the world, from committed very little-leaguers to perish-tough spectators. This article has tips to prove how pleasant baseball happens to be.

    ReplyDelete
  31. https://gamezoom.xyz Obtaining a work out spouse can significantly enhance your muscle-creating outcomes. Your spouse could be a important method to obtain motivation for sticking with your training session treatment, and pushing you to increase your initiatives whilst you exercise. Having a trustworthy spouse to work out with can also help help you stay secure because you will invariably use a spotter.

    ReplyDelete
  32. https://gameboot.xyz The truth is them on periodicals and on TV, women and men who appear to be their forearms and thighs and legs will explode his or her muscle tissue are so large! There is no will need so that you can get your system to that particular level when you don't want to, since the simple techniques on this page will help you construct muscle tissue in a healthful method.

    ReplyDelete
  33. […] you can incorporate into various projects like a festive wreath or a sign for example. Head over to hawthorneandmain for more details and instructions about […]และ บาคาร่า
    لینک های خیلی خوبی میده این سایت

    ReplyDelete
  34. How to Deal with Search in Outlook Not Working?

    Outlook users mostly have the query related to search in Outlook not working. If you are also facing the same issue then you need to restart your Outlook device properly. One can also think to repair Outlook program by using the Microsoft Inbuilt Repair tool. This tool will help you to deal with the issue smoothly without facing any other error.

    How to Silence Outlook Notifications on iPhone?

    Check out the steps properly and know how to silence Outlook notifications on iPhone, then follow the steps properly. For Gmail users, you need to click on the gear icon towards the upper right of the Gmail window. Now, choose the settings ink and then tap to mail notifications off under the Desktop notifications section. Lastly, tap to save to smoothly silence Outlook notifications on iPhone devices. Follow the steps properly to know about Outlook notifications on your iPhone device.

    Why is My Yahoo Mail Not Working?

    The possibility for users facing why is my Yahoo mail not working issue is because of technical glitches in your account. To deal with it, check for the underneath steps. For this, proceed to iPad or iPhone and then open Safari. Now, proceed to Yahoo homepage or choose the link and i.e.http://mail.yahoo.com/. Lastly, you need to login to your account and then you can send or read the emails properly. Even if everything is working properly then also you need to check account settings as there might be chances those issues lies here only.

    How to Perform Bellsouth Email Setup?

    To perform Bellsouth email setup, open Android and then open Bellsouth in your Gmail account. After that, select the menu bar option and press the drop down next to name and select the add account button. After that, you need to choose either Bellsouth settings, you can either choose POP3 settings or choose IMAP settings for configuring the email account. After that, enter password and tap on next button. Verify the POP server and type att.net for inbound server and 995 as port number. After that, enter Att.net for SMTP settings and 465 as secured security layer. These are the steps to perform Bellsouth email setup process.

    How to Recall Email Outlook App iPhone?

    If you are an iPhone user and want to know about the steps to smoothly recall email Outlook app iPhone then here’s what you have to do. For this, open web browser on iPhone and proceed to Outlook.com. Now, log into your Outlook account by using correct credentials. Now, choose sent items folder and open email that you want to recall. Locate the message tab in open window with your email. Click on recall this message under move option. Lastly, you need to replace the sent email with the new one or delete the unread email by clicking on OK.

    ReplyDelete
  35. How to Enable Java in Chrome in Windows 10?

    Check out the guide properly and know about the steps to know how to enable Java in Chrome in Windows 10. If you are using Windows and want to enable Java in Chrome browser then use the Java control panel to do it. For this, open Java control panel and choose the security tab. At the top, check to enable Java content in the browser. Now, click to apply and choose OK to confirm the changes. Lastly, you need to restart Google Chrome to enable the changes. These are the steps to follow to enable Java in Chrome in Windows 10 device.

    ReplyDelete
  36. We are really grateful for your blog post for giving a lot of information
    스포츠토토

    ReplyDelete
  37. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. 토토사이트

    ReplyDelete
  38. Wow, great article.Really looking forward to read more. 경마

    ReplyDelete

  39. CEA Aviation is one of the greatest pilot training schools in the country; if you want to be a skilled pilot, this is the place to be. Don't miss out on this opportunity to attend DGCA Ground Classes in delhi facility

    ReplyDelete
  40. Thanks for the great content,I will also share it with my friends & once again Thanks a Lot.OnlyFansYT

    ReplyDelete
  41. Great Post !! Very interesting topic will bookmark your site to check if you write more about in the future.Embedded Systems Course in Hyderabad

    ReplyDelete
  42. You had a great weekend. My neighborhood was very depressed because it rained a lot. The sun is shining brightly today. I feel good.메이저사이트

    ReplyDelete
  43. This blog is really helpful for the public .easily understand,
    Thanks for published,hoping to see more high quality article like this.
    홀덤사이트


    ReplyDelete
  44. heating masturbator cup has ultra-soft textured tunnel made of skin-like TPE features a fantastic texture, which perfectly simulates a soft and tight vag-ina with proper elasticity.

    ReplyDelete
  45. Step-by-Step Hacking Tutorials about WiFi hacking,
    Kali Linux, Metasploit, exploits, ethical hacking, information security, malware analysis and scanning
    hacking

    ReplyDelete

Popular Posts