0

大家好,我正在对 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);

    }       
}

在这里,我尝试输入错误的用户 ID 并期望抛出运行时异常。代码工作正常,它会随消息一起引发期望。但问题是它只为第一个输入调用一次,其他输入值不被执行。我怎样才能让它循环工作?注意: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);
}
4

0 回答 0