Solved

Junit Test case

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This video teaches viewers about errors in exception handling.

760 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now