预期的异常和预期的消息在循环中不起作用

时间:2016-09-29 13:31:13

标签: java unit-testing junit junit-rule

大家好我正在对Spring MVC项目进行Junit测试。这里有以下代码

要测试的方法

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;  }

我正在测试它的正面和负面情况。

这是我的否定测试用例

@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);

    }       
}

这里我试图输入错误的userID并期望抛出运行时异常。代码工作正常,它会将消息与消息一起抛出。但问题是第一次输入只调用一次,其他输入值不执行。我怎样才能让它在循环中工作? 注意:Junit测试用例通过并显示绿色条。

我已经改变了代码,但这对循环也不起作用。我在哪里做错了?

@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);
}

0 个答案:

没有答案