Hi All I am doing Junit testing on Spring MVC project. Here the following code
Method to be tested
public UserDetails getUserInfo(String userID) {
Session session = sessionFactory.getCurrentSession();
UserDetails userDetails = new UserDetails();
Query query = null;
try {
query = session.createQuery("From UserDetails where user_Id=:userID").setParameter("userID", userID);
List < UserDetails > list = query.list();
if (CollectionUtils.isNotEmpty(list)) {
userDetails = list.get(0);
} else {
throw new RuntimeException("No identifier found on our records! for '" + userID + "'");
}
} catch (Exception e) {
throw e;
}
return userDetails; }
I am testing it for both positive and negative cases.
Here is my negative testcase
@Autowired
DaoLayer layer;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
@Transactional
public void getUserInfoNegative() throws Exception
{
String[] inputs={"W12348","ABCDEF","123456"};
for(int i=0;i<inputs.length;i++)
{
System.out.println("/****** Invoking getUserInfo with Input "+inputs[i]+" *********/");
String msg="No identifier found on our records! for '"+inputs[i]+"'";
thrown.expect(RuntimeException.class);
thrown.expectMessage(msg);
layer.getUserInfo(input);
}
}
Here I am trying to input wrong userID's and expecting runtime exception to be thrown. The code works fine it throws the expection along with the message. But the issue is it is invoking only one time for the first input, other input values are not executed. How Can I make it to work in loop?? Note: Junit testcase passed and shows green bar.
I have altered the code but that too doesnot work for loop. Where I am doing wrong??
@Test
@Transactional
public void getUserInfoNegative() throws Exception
{
String[] inputs={"W12348","ABCDEF","123456"};
for(int i=0;i<inputs.length;i++)
{
System.out.println("/****** Invoking getUserInfo with Input "+inputs[i]+" *********/");
String msg="No identifier found on our records! for '"+inputs[i]+"'";
getUser(msg,inputs[i]);
}
}
public void getUser(String msg,String input)
{
thrown.expect(RuntimeException.class);
thrown.expectMessage(msg);
layer.getUserInfo(input);
}