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