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

78 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. I am a newbie in Annotations.Kindly let me know what will happen if we pass parameters to @Test like expected=Exception.class

    ReplyDelete
  8. 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
  9. 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
  10. KGF 2 : Directed by Prashanth Neel. With Yash, Sanjay Dutt, Raveena Tandon, Prakash Raj. The blood-soaked land of Kolar Gold Fields

    ReplyDelete
  11.   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
  12. 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
  13. 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
  14. 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
  15. 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
  16. thanks for sharing nice blog keep post https://duckcreektraining.com/

    ReplyDelete
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. […] 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
  25. 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
  26. 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
  27. 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

  28. 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
  29. 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
  30. This blog is really helpful for the public .easily understand,
    Thanks for published,hoping to see more high quality article like this.
    홀덤사이트


    ReplyDelete
  31. 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
  32. Step-by-Step Hacking Tutorials about WiFi hacking,
    Kali Linux, Metasploit, exploits, ethical hacking, information security, malware analysis and scanning
    hacking

    ReplyDelete
  33. This comment has been removed by the author.

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. He is equally kind and cruel. This blog is extremely cool. The link is a great resource. Many blog readers have benefited greatly from the information you have provided for them.
    Manual Testing Course

    ReplyDelete
  37. well, that's was a very informative blog.Keep up the good work and checkout this java training in pune

    ReplyDelete
  38. A drag-and-drop interface that makes it easy to build integrations
    A wide range of pre-built connectors for popular applications and systems
    A robust API management platform
    A built-in workflow engine
    A variety of security features
    Dell Boomi is a powerful iPaaS platform that can help businesses of all sizes connect their applications, data, and systems. It is a scalable, flexible, and secure platform that is backed by a team of experienced professionals.

    ReplyDelete
  39. Unit 4.0 introduced a new API that utilizes Java 5 annotations for describing tests, providing a more flexible and streamlined approach compared to the inheritance-based approach of older versions. This post will highlight some of the key features in JUnit 4 and provide a basic example that tests the java.util.Stack class.

    In JUnit 4, you no longer need to extend TestCase to implement tests. Instead, you can use a simple Java class as a test case. The test methods are annotated with org.junit.Test annotation. Here's an example:
    java

    import org.junit.Test;
    import static org.junit.Assert.*;

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

    In the above example, the emptyTest method is annotated with @Test, indicating that it is a test method. Inside the test method, assertions can be made using the provided assert methods. However, since JUnit 4 test classes do not inherit from TestCase, the assert methods are not available by default.

    To use the assert methods, you have two options: either use the prefixed syntax (Assert.assertEquals()) or import the Assert class statically. Here's an example using static import:
    java

    import org.junit.Test;
    import static org.junit.Assert.*;
    import static org.junit.Assert.assertEquals;

    public class StackTest {
    @Test
    public void emptyTest() {
    Stack stack = new Stack<>();
    assertTrue(stack.isEmpty());
    assertEquals(0, stack.size());
    }
    }

    By statically importing Assert.assertEquals(), you can use it directly in the test method without prefixing it with Assert.

    These are just some of the basic features and usage patterns in JUnit 4. The framework also provides other advanced features like initialization and cleanup methods, timeouts, and parameterized test cases, among others.
    Jobs Listings
    Visit Serafelagi.com!
    I hope this gives you a brief overview of writing unit tests with JUnit 4. If you have any further questions or need additional assistance, feel free to ask!

    ReplyDelete
  40. Good explanation about the Java 9 Features with Examples, Unit Testing with JUnit 4.0, thanks for sharing, and looking for more
    Power BI Training institute in KPHB

    ReplyDelete
  41. شركة تنظيف بالدمام
    خدمات النظافة المتكاملة في الدمام: تضمن الراحة والجودة

    ReplyDelete
  42. This is incredible, I feel really happy to have seen your webpage.

    ReplyDelete
  43. I gained much unknown information, the way you have clearly explained is really fantastic.

    ReplyDelete

Popular Posts