Wednesday, 30 August 2017



      Definition
    •  Unit testing is a process of testing a single unit in isolation by passing inputs to it. A unit can be a single method or a combination of methods.
    • In Junit we will pass different inputs to a unit and checking whether we are getting expected output.
    • The test files should be in a different folder. We don’t want to mix test and the src files. Because we are not going to deploy test classes.
    • We can use any name to test classes. Usually we will create test class like “className+Test”.
    • JUnit always success unless there is no condition. Junit Failure means we have condition in test method and it  is failed.
    • When a test method having multiple condition and the middle condition got failed. Then the remaining conditions will not process.
    • If we made any changes in existing source code and we need to check whether it is working with all conditions. Then we just need to run JUnit and verify.
    1.      Example        
          Class to be test(StringHelper.java)
    public class StringHelper { public String truncateInFIrst2Positions(String str) { if (str.length() <= 2) { return str.replaceAll("A", ""); } String first2Charecters = str.substring(0, 2); String stringMinusFirst2Charecters = str.substring(2); return first2Charecters.replaceAll("A", "") + stringMinusFirst2Charecters; } public boolean areFirstAndLastTwoCharectersSame(String str) { boolean output = false; if (str.length() >= 4) { String first2Chaecters = str.substring(0, 2); String last2Charecters = str.substring(str.length() - 2); if (first2Chaecters.equals(last2Charecters)) { output = true; } } return output; } }      

    The Test Class


    public class StringHelperTest { private StringHelper helper=null; @Before public void before() { helper = new StringHelper(); System.out.println("Executes Before"); } @After public void After() { helper = null; System.out.println("Executes After"); } @BeforeClass public static void beforeClass() { System.out.println("Executes beforeClass"); } @AfterClass public static void AfterClass() { System.out.println("Executes AfterClass"); } @Test public void truncateInFIrst2PositionsTest() { System.out.println("truncateInFIrst2PositionsTest"); String expectedOutput = "RM"; String actualOutput = helper.truncateInFIrst2Positions("AARM"); Assert.assertEquals(expectedOutput, actualOutput); Assert.assertEquals("WERT", helper.truncateInFIrst2Positions("WERT")); Assert.assertEquals("WRM", helper.truncateInFIrst2Positions("AWRM")); Assert.assertEquals("RM", helper.truncateInFIrst2Positions("ARM")); Assert.assertEquals("AA", helper.truncateInFIrst2Positions("AAAA")); } @Test public void areFirstAndLastTwoCharectersSameTest() { System.out.println("areFirstAndLastTwoCharectersSameTest"); Assert.assertTrue(helper.areFirstAndLastTwoCharectersSame("WEERWE")); Assert.assertFalse(helper.areFirstAndLastTwoCharectersSame("WEERUE")); } @Test public void arraySortTest() { int[] arr = {2,4,5,3,1}; Arrays.sort(arr); int[] expectedOutput = {1,2,3,4,5}; Assert.assertArrayEquals(expectedOutput, arr); } @Test(expected=NullPointerException.class) public void chkExceptionTest() { int[] arr = null; Arrays.sort(arr); } @Test(timeout=10) public void arraySortPerformanceTest() { for(int i=0; i<100000 arr="" arrays.sort="" code="" i-1="" i="" int="">

    Adding JUnit in Eclips
          Right click your project in Package Explorer > click Properties
          go to Java Build Path > Libraries tab
          click on 'Add Library' button
          select JUnit
          click Next.

    Annatations
     @Test
         It  will tells the method is a test condition.
     @Test(expected=NullPointerException.class)
         Test will pass only if a NullPointerException has thrown.
     @Test(timeout=10)
         Test will pass only if the execution would complete within given timeout.
    @Before
        The void method which is annotated with  @Before will execute before each test method.
    @After
        The void method which is annotated with  @After will execute after each test method.
    @BeforeClass
       The void method which is annotated with  @BeforeClass will execute before test class start execution.
    @AfterClass
        The void method which is annotated with  @AfterClass will execute after test class execution.

    Basic Asserts
     Assert.assertEquals(expectedOutput, actualOutput)
           Comparing expectedOutput vs actualOutput and pass only when both are equals.
    Assert.assertArrayEquals(expectedOutput, actualOutput)
           Comparing both arrays  and pass only when both are equals.
     Assert.assertTrue(boolean arg)
           Pass condition only when the Boolean argument is true.
    Assert.assertFalse(boolean arg)
           Pass condition only when the Boolean argument is false.

    Spy vs Mock
        Mock
    •         Mock always returns default values. It cannot do anything what actual arraylist does.
    •         We can only stub the arrayList  to some values.
    •         Mock is dummy implementation.
    •          No logics from object can be used.
    •          If we add one element then its size will not change.


    @Test public void mockTest() { List mockList = Mockito.mock(ArrayList.class); Assert.assertEquals(0, mockList.size()); Mockito.stub(mockList.size()).toReturn(5); Assert.assertEquals(5, mockList.size()); }

        Spy
    •      Spy will create an actual object and it will do all logical operations unlike mock does.
    •       We are able to add element and increase size. But this size can be change to mock size using stub.
    •       We can override actual values using stub. 
    •        Spy will let the real logic to be done and also can be change real behavior when needed.



    @Test public void spyTest() { List mockList = Mockito.spy(ArrayList.class); mockList.add("SONU"); Assert.assertEquals(1, mockList.size()); Mockito.stub(mockList.size()).toReturn(5); Assert.assertEquals(5, mockList.size()); }

    Monday, 28 August 2017

    1. Please go through this tutorial to understand the basic concept
    2. List returned by Arrays.asList(): it is documented not to support any removing or adding elements. 
    3. If we update a list from a method X by calling another void method Y, list modification will be affected in the list object in the method X.
    4. Because the the same object memory is used when passing the reference. So java is Pass by value. 
    public class MemoryTest { public static void main(String[] args) { MemoryTest mt = new MemoryTest(); mt.scopeTest(); } private void scopeTest() { int numberInt = 2; Integer numberInteger = 10; List numberList = new ArrayList(); numberList.add(10); numberList.add(20); Student student = new Student(); student.setId(1); student.setName("Sonu"); MemoryTest mt = new MemoryTest(); System.out.println("numberInt before = " + numberInt); mt.modifyInt(numberInt); System.out.println("numberInt after = " + numberInt); System.out.println("numberInteger before = " + numberInteger); mt.modifyInteger(numberInteger); System.out.println("numberInteger after = " + numberInteger); System.out.println("numberList before = " + numberList); mt.modifyList(numberList); System.out.println("numberList after = " + numberList); System.out.println("student before = " + student); mt.modifyStudent(student); System.out.println("student after = " + student); } private void modifyInt(int i) { i = 3; } private void modifyInteger(Integer i) { i = 200; } private void modifyList(List list) { list.add(100); } private void modifyStudent(Student student) { student.setId(2); student.setName("Sreenu"); } }

    Output

    numberInt before = 2 numberInt after = 2 numberInteger before = 10 numberInteger after = 10 numberList before = [10, 20] numberList after = [10, 20, 100] student before = 1, Sonu student after = 2, Sreenu

    Search This Blog

    Contact us

    Name

    Email *

    Message *