模拟依赖项和代码覆盖率工具显示未执行的代码

时间:2017-03-01 13:43:04

标签: java unit-testing junit mocking jmockit

我试图将我的bean作为一个组件进行测试。这样我想测试的方法就可以正确执行了。因此,我嘲笑它与JMockit的依赖关系。我编写了两个测试,一个用于验证if条件为true,因此方法立即结束并返回null。第二个用于执行此条件下面的代码也导致返回null。但是我的代码覆盖率工具(JaCoCo)只是显示if条件被执行而不是下面的代码。 Session是超类ÀbstractBean中的一个字段。方法isLoggedIn()调用session.isLoggedIn(),并在AbstractBean中定义。

TrendBean

@Named(value = "trendBean")
@ViewScoped
@SuppressWarnings("deprecation")
public class TrendBean extends AbstractBean implements Serializable {

private static final long serialVersionUID = -310401000218411384L;

private static final Logger logger = Logger.getLogger(TrendBean.class);

private ChartPoint point;

private List<ChartPoint> points;

@Inject
private ITrendManager manager;


public String addChartPoint() {
    if (!isLoggedIn()) {
        return null; //only this block is executed
    }
    assertNotNull(point);
    final User user = getSession().getUser();
    manager.addPointToUser(user, point);
    FacesContext.getCurrentInstance().addMessage(
            null,
            new FacesMessage(FacesMessage.SEVERITY_INFO,
                    getTranslation("pointAdded"), ""));
    init();
    return null;

    }
}

TrendBeanTest

public class TrendBeanTest {

@Tested
TrendBean trendBean;
@Injectable
LoginBean loginBean;
@Injectable
Session session;
@Injectable
ITrendManager manager;
@Injectable
IUserManager userManager;

@Test
public void testAddChartPoint() {

    new NonStrictExpectations() {

        {
            session.isLoggedIn();
            result = true;
            session.getUser();
            result = (User) any;
            manager.addPointToUser((User) any, (ChartPoint) any);
        };
    };

    Deencapsulation.setField(trendBean, "point", new ChartPoint());

    assertEquals(null, trendBean.addChartPoint());

}

@Test
public void testAddChartPointNotLoggedIn() {

    new Expectations() {
        {
            manager.addPointToUser((User) any, (ChartPoint) any);
            times = 0;
        };
    };

    Session s = new Session();
    s.setUser(null);

    Deencapsulation.setField(trendBean, "session", s);

    assertEquals(null, trendBean.addChartPoint());

    }
}

AbstractBean

public abstract class AbstractBean {

private static final Logger logger = Logger.getLogger(AbstractBean.class);

@Inject
private Session session;

public boolean isLoggedIn() {
    return session.isLoggedIn();
}
} 

1 个答案:

答案 0 :(得分:0)

对于任何熟悉问题的人来说

session.isLoggedIn();
result = true;
在Expectations Block中,

就是答案。虽然我面临新问题,但我会问一个新问题。