Solved

Junit Test case

Posted on 2013-12-16
4
667 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 35

Accepted Solution

by:
mccarl earned 500 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 35

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
table example 4 32
hibernate example for saving data 19 57
JAVA API design with micro service cloud in mind 1 49
Glassfish admin console not working 1 35
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…
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

828 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