2

I have a utility method that I wanted to write a unit test for. Since this utility runs under a webapp, it is designed to get a Spring bean from the WebApplicationContext.(follow code is not under unit test) action bean class

private IUnitBiz unitBiz;
public UnitBean()
{
    unitBiz = CommonUtils.getBean(IUnitBiz.class);
}

in CommonUtils.class

public static ApplicationContext getWebApplicationContext() {
        return FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
    }

    public static <T> T getBean(Class<T> beanType) {
        return getWebApplicationContext().getBean(beanType);
    }

------------------in unit test----------------

In unit test it is return null, how can i init WebApplicationContext or getBean for my unit test? when i new action bean, getBean method is return null.

2 Answers 2

2

EasyMock could be a solution.

Example:

WebApplicationContext mockWebApplicationContext = EasyMock.createMock(WebApplicationContext.class);
MockServletContext mockServletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                                    mockWebApplicationContext);

EasyMock.expect(mockWebApplicationContext.getServletContext()).andReturn(mockServletContext).anyTimes();
Sign up to request clarification or add additional context in comments.

1 Comment

i want to get bean from this method
0

You could make your test case extends org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests.

By extending this class, you can access an instance of the org.springframework.context.ApplicationContext, which can be used and passed along your utility methods... Actually, I don't know if you're using but you should try spring-test, it's the best way to use Spring in JUnit tests and it's framework independent (it can be used with Wicket, JSF, etc.).

You should start by including the dependency below in your Maven pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.0.0.RELEASE</version>
    <scope>test</scope>
</dependency>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.