Mock @org.jboss.seam.annotations.in behaviour for unittest

有些话、适合烂在心里 提交于 2019-12-13 05:41:55

问题


The test:

public class BeanTest {

    private SomeBean target;

    @Test(groups = "integration")
    public void checkIfAuthenticationWorks() {

        ApplicationBean applicationBean = mock(ApplicationBean.class);
        target = new SomeBean();

        // Some cool code to inject applicationBean to target class

        assertEquals("token", target.authenticate(USERNAME, PASSWORD));
    }
}

The class:

@AutoCreate
@Name("someBean")
@Scope(ScopeType.SESSION)
public class someBean implements Serializable {

    @Logger
    private static Log log;

    @In
    ApplicationBean applicationBean;

    public String authenticate(String username, String password) {

     // Very cool code!

    return "token";
    }
}

Is there some smart way of solving the applicationBean injection part?

// Jakob


回答1:


First, make the test the Seam way, that is extending SeamTest:

public class BeanTest extends SeamTest {

    private SomeBean target;

    @Test(groups = "integration")
    public void checkIfAuthenticationWorks() {

        target = (SomeBean) Component.getInstance(SomeBean.class);
        // target get injected with the MockApplicationBean


        assertEquals("token", target.authenticate(USERNAME, PASSWORD));
    }
}

Then, create a MockApplicationBean with MOCK precedence and put it in the test classpath so that it will be injected in place of the real ApplicationBean:

@Name("applicationBean")
@Install(precedence = MOCK)
public class MockApplicationBean extends ApplicationBean
{
  // your mocked ApplicationBean  

}

Finally, note that target must be instantiated as a Seam component, not with "new":

SomeBean target = (SomeBean) Component.getInstance(SomeBean.class);


来源:https://stackoverflow.com/questions/5538754/mock-org-jboss-seam-annotations-in-behaviour-for-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!