Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Junit Test case

Posted on 2013-12-16
4
Medium Priority
?
743 Views
Last Modified: 2013-12-28
Good Day,

I am new to Junit... can i  know  how to write the junit on these method

public class MergeMp 

	public static final String FROM_ID_SET_NAME = "fromID";
	public static final String TO_ID_SET_NAME = "toID";
	
	public Merge mapFieldSet(FieldSet fieldSet)
			throws BindException {
		if(fieldSet == null){
			return null;
		}
		
		Merge mm = new Merge();
		mm.setMidFrom(fieldSet.readString(FROM_ID_SET_NAME));
		mm.setMidTo(fieldSet.readString(TO_ID_SET_NAME));		

		return mm;
	}
}

Open in new window


I have a sample DAO class I like to know how to write a Junit Testcase

public class MidDAOImpl implements MidDAO{
	
	private static final String UPDATE_SQL = "UPDATE Product SET M_ID = ? WHERE M_ID = ?";
	private static final String UPDATE_SQL1 = "UPDATE product_details SET M_ID = ? WHERE M_ID = ?";
	
	private static final Log log = LogFactory.getLog(MidDAOImpl.class);
	
    private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
	
	
	
	public void compareM(List<? extends MidM> midList) throws SQLException,MidException{
		try{
			
			boolean flag = true;
			int rows = 0;	
			
			
			
			for(Mid mid : midList){
				rows = 0;				
				rows = jdbcTemplate.update(UPDATE_SQL, prepareMerge(mid));
				rows += jdbcTemplate.update(UPDATE_SQL1, prepareMerge(mid));
				
				// updating the row updates in the output file
				if(rows!=0){
					log.info(mid.getMidFrom()+","+mid.getMidTo()+","+rows+","+"Updated Matched ID Records");
					flag = false;
				}
			}
			
			if(flag){
				log.info("--- No Matched ID records found ---");					
			}
			log.info("--------------------------------------");
			
		}catch(Exception e){
			throw new MidException(e.getMessage());
		}
	}
	
	/**
	 * @param mm
	 * @return Object
	 */
	private Object[] prepareMid(Mid mm) throws MidException{		 
		Object[] mmObj = {mm.getMidTo(),mm.getMidFrom()};
		
		return mmObj;
	}			
}

Open in new window

0
Comment
Question by:roy_sanu
  • 2
  • 2
4 Comments
 
LVL 36

Accepted Solution

by:
mccarl earned 2000 total points
ID: 39722983
I am new to Junit... can i  know  how to write the junit on these method
Can you post the code for the Merge and the FieldSet classes (or provide a link to Javadoc for them, if they are classes provided by 3rd party library). However in the absense of the above, a JUnit test case would look something like this...
public class MergeMpTest {
    private MergeMp mergeMp;

    @Before
    public void beforeTest() {
        mergeMp = new MergeMp();
    }

    @Test
    public void testMergeMp() {
        FieldSet input = new FieldSet();                  //
        input.setString("fromID", "foo");                 //
        input.setString("toId", "bar");                   // These 3 lines are just a guess and would change depending on how FieldSet is coded

        Merge result = mergeMp.mapFieldSet(input);

        assertEquals("foo", result.getMidFrom());     //
        assertEquals("bar", result.getMidTo());       // These 2 lines are also just a guess that the .getXXX() methods are available on the Merge class
    }
}

Open in new window




I have a sample DAO class I like to know how to write a Junit Testcase
Generally, I wouldn't worry about unit testing a DAO, and just leave that for integration testing. You could mock the jdbctemplate but there isn't really much code left that is actually getting tested. I would generally leave the unit testing for your service layer code that is actually manipulating objects and possibly doing calculations, etc.
0
 

Author Comment

by:roy_sanu
ID: 39723211
 FieldSet input = new FieldSet();

Open in new window

it is giving the errors as "Cannot instantiate the type FieldSet" as it an Interface
0
 
LVL 36

Expert Comment

by:mccarl
ID: 39723578
it is giving the errors as "Cannot instantiate the type FieldSet" as it an Interface
As I said, that code was just a guess because I don't know what FieldSet is. And since you haven't provide the code (or a link to the library) as I asked for, I am going to assume that maybe you are using Spring Batch and that is where FieldSet comes from?

If so, you will need to use a test case more like this...
public class MergeMpTest {
    private MergeMp mergeMp;

    @Before
    public void beforeTest() {
        mergeMp = new MergeMp();
    }

    @Test
    public void testMergeMp() {
        FieldSet input = new DefaultFieldSet(new String[] { "foo", "bar" }, new String[] { "fromID", "toID" });

        Merge result = mergeMp.mapFieldSet(input);

        assertEquals("foo", result.getMidFrom());     //
        assertEquals("bar", result.getMidTo());       // These 2 lines are also just a guess that the .getXXX() methods are available on the Merge class
    }
}

Open in new window

0
 

Author Comment

by:roy_sanu
ID: 39726619
Hi,

Here is the code base for the DAO class
 

public class MidDAOImpl implements MidDAO{
	
private static final String UPDATE_SQL = "UPDATE Product SET M_ID = ? WHERE M_ID = ?";
private static final String UPDATE_SQL1 = "UPDATE product_details SET M_ID = ? WHERE M_ID = ?";
	
private static final Log log = LogFactory.getLog(MidDAOImpl.class);
	
 private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
	
	
	public void compareM(List<? extends MidM> midList) throws SQLException,MidException{
		try{
			
			boolean flag = true;
			int rows = 0;	
			
			
			
			for(Mid mid : midList){
				rows = 0;				
				rows = jdbcTemplate.update(UPDATE_SQL, prepareMid(mid));
				rows += jdbcTemplate.update(UPDATE_SQL1, prepareMid(mid));
				
				// updating the row updates in the output file
				if(rows!=0){
					log.info(mid.getMidFrom()+","+mid.getMidTo()+","+rows+","+"Updated Matched ID Records");
					flag = false;
				}
			}
			
			if(flag){
				log.info("--- No Matched ID records found ---");					
			}
			log.info("--------------------------------------");
			
		}catch(Exception e){
			throw new MidException(e.getMessage());
		}
	}
	
	/**
	 * @param mm
	 * @return Object
	 */
	private Object[] prepareMid(Mid mm) throws MidException{		 
		Object[] mmObj = {mm.getMidTo(),mm.getMidFrom()};
		
		return mmObj;
	}			
}

Open in new window



is this the correct approach to use the easy mock for testing DAO class


import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.easymock.classextension.EasyMock.createMock;


@RunWith(SpringJUnit4ClassRunner.class)
public class MidMergeDaoTest {
	
private static final String UPDATE_SQL = "UPDATE Product SET M_ID = ? WHERE M_ID = ?";
private static final String UPDATE_SQL1 = "UPDATE product_details SET M_ID = ? WHERE M_ID = ?";

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		
		
		MidDAOImpl mid = new MidDAOImpl ();
		mid = createMock(MidDAOImpl .class);
	//	final PreparedStatement ps = (PreparedStatement) psControl.getMock();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		
		
		
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() {
		DataSource dataSourceMock = createMock(DataSource.class);
		Connection connectionMock = createMock(Connection.class);
		JdbcTemplate mockJdbcTemplate = createMock(JdbcTemplate.class);
		PreparedStatement preparedStatementMock = createMock(PreparedStatement.class);
		
		
		 
		 mockJdbcTemplate.execute(UPDATE_SQL );
		 mockJdbcTemplate.execute(UPDATE_SQL1 );
		
	
	     
	}
	

}

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question