Loading
UnitTesting Interview Questions

Java Quick Notes

Refresh Your Java

We are Agile, believe in less Documentation - Only Quick notes of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

"Click on other Tabs for more Questions"  

"UnitTesting "


UnitTesting is very important in development life cycle, this section focuses on Unit Testing methodologies.

1 )   What is Unit Testing ?


Ans)

In computer programming, Unit testing is a method by which individual units of source
code
, sets of one or more computer program modules together with associated control data,
usage procedures, and operating procedures, are tested to determine if they are fit
for use.one can view a unit as the smallest testable part of an application. In
object-oriented programming a unit is often an entire interface, such as a class,
but could be an individual method.

In Java World there are so many APIs which could be used for performing Unit Testing,
including JUNIT,  CACTUS, MOCKITO,STRUTSUNIT, SELENIUM .

 



Back to top

2 )   JUnit Unit Testcase Example ?


Ans)

JUNIT is a very popular Unit Tesing API, this has been widely used
for performning Unit Testing.

Below are steps to follow for creating a JUNIT Test Case.

public class TestYourService extends TestCase {
 
 protected void setUp()  {
  try {
   super.setUp();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
 }

 protected void tearDown() throws Exception {
  super.tearDown();
 }

 public void testYourMethod() throws ComergentException {
         TestService testService = new TestServiceImpl();     
         String result = testService.perform();
         assertNotNull(result);
         assertEquals("Success", result);
   }
}



Back to top

3 )   Cactus Unit Testcase Sample ?


Ans)

Cactus is used for Unit Testing of the source code which requires a Servlet Containers
meaning which requies HTTPServletRequest, HTTPServletResponse.

Step 1:

import org.apache.cactus.ServletTestCase;
import org.junit.Test;

public class YourCactusTest extends ServletTestCase {

 protected void setUp() throws Exception {
  Cache.reLoadCache();
 }
  
 @Test
 public void testFillPriceLines ()  {
  assertEquals(2, hboCount);
  assertEquals(3, premierCount);
 }
 
 @Test
 public void testFillPriceLinesOnlyHBO ()  {
  assertEquals(2, hboCount);
 }
}


Step 2:

Deploy your test in a Servlet Container and use the following URL to
run the Test.

http://host:port/yourApp/ServletRedirector?Cactus_Service=RUN_TEST
Or
http://host:port/yourApp/ServletTestRunner?suite=YourCactusTest

Step 3 :

Add the Following to web.xml

  <servlet>
    <servlet-name>ServletRedirector</servlet-name>
    <servlet-class>org.apache.cactus.server.ServletTestRedirector</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>ServletTestRunner</servlet-name>
    <servlet-class>org.apache.cactus.server.runner.ServletTestRunner</servlet-class>
  </servlet>



Back to top

4 )   Unit Testing of Struts Action Class.


Ans)

"Servletunit" should be used to perform the Unit Testing of the Struts actions also as we need ServletRequest/Response etc.,  for this.

 "MockStrutsTestCase" should be used for this purpose. Please see below for full example.

Step 1 :

Please download "servletunit" jar

Step 2:

Your Test Case should extend "MockStrutsTestCase".

Step 3:

Create your TestCase as follows .

public class EditActionTest extends MockStrutsTestCase {
public EditActionTest(String name) {
  super(name);
 }
 public void tearDown() throws Exception {
        closeSession();
 }

   public void test_update() throws Exception{

  addRequestParameter("method", "update");
  addRequestParameter("contactId", "273016914");
  addRequestParameter("reloadContact", "false");
  addRequestParameter("zipCode", "08053");
  addRequestParameter("address1" , new String[]{"225 Test road", "Apt 6","Test City","Test State"});
  
  setRequestPathInfo("/contactDetailsEdit");
  actionPerform();
  verifyForwardPath("/contactDetails.do?contactId=273016914");

  verifyNoActionErrors();
  assertEquals(request.getAttribute("isAddressVarified"), true);

 }

 @Test
 public void test_getContactData() throws Exception {

  ContactForm form = new ContactForm();
  HttpServletRequest request = createMock(HttpServletRequest.class);
 
 BigDecimal oppObjid = new BigDecimal("273028572");

  Contact opportunity = (Contact) ContactServices
    .getOpportunityByObjid(oppObjid);
 }
}



Back to top

5 )   JMockito Unit Testcase Example ?


Ans)


Junit has some limitaions , for instance we could not test the Private and Static methods
with JUNIT, this issue is addressed by some other Unit Testing APIs such EasyMock, Mockito
and all.

Here is the sample Mocktio Unit Test case.

Step 1 :
Util class which has a Static Method.

class TestUtil {
 
 public static printName (Srting name ) {
  
  System.out.println("Your Name is " + name);
 }
}

Step 2 :
 Your service that to be tested.

class YourService {
 public YourService() {
  
 }
 public void printName (Srting Name) {
  TestUtil.printName(Name);
 }
}

Step 3:
Your Test Case

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.whenNew;


import org.apache.tools.ant.taskdefs.Length.When;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ TestUtil.class})

public class TestBroadBandService {
 
 @Before
 public void createData() {
     PowerMockito.mockStatic(TestUtil.class);
  when (TestUtil.printName("") .thenReturn("newName");
 }

   @Test
 public void testInvokeWebService() {
  YourService YourService = new YourService();
  yourService.printName("YourName");
 }
}



Back to top

6 )   Spring Unit Testing


Ans)

Full Spring Unit Testing Example.

If you want to perform unit testing for your Spring Classes, you have to use "SpringJUnit4ClassRunner",

Please follow the below steps to create Unit Test cases for Spring Classes.

Step 1:
Use "@RunWith" annotation as follows.
    @RunWith(SpringJUnit4ClassRunner.class)

Step 2:  
Provide the path of Spring Config file as shown below.
     @ContextConfiguration(locations={"file:C:\\salesorder\\web\\WEB-INF\\applicationContext-Contact.xml"})

Step 3:
Use "@Autowired" for the Java class that you want to be loaded by Spring as shown below.
  @Autowired
    ContactServices ContactServices;
 
Example :
 
import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

import javax.servlet.ServletException;

import org.hibernate.classic.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


import com.salesorder.enumtypes.EnumConditions;
import com.salesorder.Contact.services.ContactServices;

import com.salesorder.hibernate.Address;
import com.salesorder.hibernate.HibernateConfig;
import com.salesorder.hibernate.Contact;
import com.salesorder.user.services.ProfileServices;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"file:C:\\salesorder\\web\\WEB-INF\\applicationContext-Contact.xml"})

public class ContactServiceTest {
  
    @Autowired
    ContactServices ContactServices;

 public ContactServiceTest (){
        try {
   new HibernateConfig().init();
  } catch (ServletException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
     }

 @Test
 public void testCreateContact() throws BLException {       
  
        Address address = new Address();
        String ContactName = "Test" + System.currentTimeMillis();

        address.setAddress("TEST");
        address.setAddress2("TEST1");
        address.setZipcode("19087");
        address.setState("PA");

        Contact Contact = new Contact();
        Contact.setName(ContactName);

        Contact = ContactServices.createContact(Contact, address);
        assertTrue("Contact Not Created", !(Contact == null));     
         
    }
       
 @Test
 public void testFindContactsWithInfo() throws BLException {
               
        List Contacts = ContactServices.findContacts(EnumConditions.BEGINS_WITH, null,
          EnumConditions.BEGINS_WITH, "TEST", EnumConditions.BEGINS_WITH, "TEST",
          EnumConditions.BEGINS_WITH, null, EnumConditions.BEGINS_WITH, "PA",
          EnumConditions.BEGINS_WITH, "19087");

        assertTrue("incorrect search result", Contacts.size() > 0);
        System.out.println("No. of Contacts found " + Contacts.size());       
         
    } 
 
 @Test
 public void testFindContactByContactId() throws BLException {
   Contact contact = ContactServices.findContactByContactID(new BigDecimal(12345));
      
    }   
}



Back to top

7 )   Selenium Unit Testcase ?


Ans)

Stay Tuned



Back to top

8 )   How to write an Unit Test Case for a Hibernate Class?


Ans)


Step 1:
Hibernate Classes also should be tested as normal classes, with exception of passing the
hibernate Properties files as follows.

System.setProperty("hibernate.properties.file.name", "hibernate_junit.properties");

Step 2:
In Hiberante Properties file or XML file you need to use dbcp Connection API as follows.

hibernate.dialect org.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.url jdbc:oracle:thin:@HostName:1522:DBName

hibernate.connection.username sa
hibernate.connection.password yourPassword
hibernate.connection.pool_size 5
hibernate.dbcp.poolPreparedStatements true
#hibernate.dbcp.ps.maxActive
hibernate.connection.provider_class com.salesorder.DBCPConnectionProvider

Step 3 :
Create Your own DBCPConnectionProvider as follows

public class DBCPConnectionProvider implements ConnectionProvider {

    private static final Log log = LogFactory.getLog(DBCPConnectionProvider.class);
    private static final String PREFIX = "hibernate.dbcp.";
    private BasicDataSource ds;
}

Step 4:
Write a TestCase as follows

public class SalesOrderTestCase extends TestCase {

    static {
        try {
            System.setProperty("hibernate.properties.file.name", "hibernateDEV_junit.properties");
            new HibernateConfig().init(null);
        }
        catch (Exception ex) {
            System.err.println("Could not initialize Hibernate Config");
            throw new RuntimeException("Could not initialize Hibernate Config");
        }
    }

    public SalesOrderTestCase() {
        super("SalesOrderTestCase");
    }

    public SalesOrderTestCase(String name) {
        super(name);
    }

    /**
     * override this in a subclass if you want to setup a separate principle than
     * nkuppili.
     */
    public void setUp() throws Exception {
     super.setUp();
    }

    public void tearDown() throws Exception {
        HibernateConfig.closeSession();
    }
}

 



Back to top

9 )   Web Service Testing with SOAP UI ?


Ans)


  • Web Service Testing  with SOAP UI ?
    Sample Img 9

We could use SOAP UI to test the Web Services before Completing the Client implementation

to test if the Service is functional as expected .

Please take a look at above Image for getting an idea how the SOAPUI looks like.



Back to top

Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,

This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.




Face Book

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free

Go To Site Map