简体   繁体   中英

junit spring - @BeforeClass run before @ContextConfiguration

I want to make a login manually with spring security in junit test, So I use @WebAppConfiguration and the @BeforeClass setUp() method to set the springcontext so that the springsecurity code can use.
But since the @BeforeClass run before the junit class annotation @WebAppConfiguration and @ContextConfiguration , so the @Autowired of private WebApplicationContext wac is null in setUp() and cause the error msg below.
Then I change the @BeforeClass to @Before then the problem solved.
Is there any way that still use @BeforeClass and can also solve the problem?

test class

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;


@ContextConfiguration(locations = {
    "classpath:/springTest/applicationContext_test.xml",
    "classpath:/applicationContext-security.xml",
    "classpath:/spring/applicationContext-repository.xml"
    })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class xxxTest {

  @Autowired
  private xxx target;

  @Autowired
  private LoginAuthenticationProvider loginAuthenticationProvider;

  @Autowired
  private WebApplicationContext wac;

  //set the context
  @BeforeClass
  public void setUp() throws ServletException {
    ServletContextListener listener = new ContextLoaderListener(wac);
    ServletContextEvent event = new ServletContextEvent(new MockServletContext(""));
    listener.contextInitialized(event);
  }

  //mock login(manually login)
  @Test
  public void test01() {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
    Authentication authentication = loginAuthenticationProvider.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    //other test code......
  }


}

error message

2018-10-10 19:18:48,006 [main] INFO  [org.springframework.test.context.web.WebTestContextBootstrapper] - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@769e7ee8, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@5276e6b0, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@71b1176b, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6193932a]
2018-10-10 19:18:48,038 [main] INFO  [org.springframework.mock.web.MockServletContext] - Initializing Spring root WebApplicationContext
2018-10-10 19:18:48,038 [main] INFO  [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initialization started
2018-10-10 19:18:48,166 [main] INFO  [org.springframework.web.context.support.XmlWebApplicationContext] - Refreshing Root WebApplicationContext: startup date [Wed Oct 10 19:18:48 CST 2018]; root of context hierarchy
2018-10-10 19:18:48,216 [main] INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
2018-10-10 19:18:48,218 [main] ERROR [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:614)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:515)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at ericsson.rtm.service.chache.xxxTest.setUp(xxxTest.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at mockit.integration.junit4.internal.JUnit4TestRunnerDecorator.invokeExplosively(JUnit4TestRunnerDecorator.java:33)
    at mockit.integration.junit4.internal.MockFrameworkMethod.invokeExplosively(MockFrameworkMethod.java:44)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
**Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]**
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 34 more

@BeforeClass is a static Method that's the reason @Autowired variable are giving null. 1) One approach which can be used is using custom boolean flag:

private static boolean isInitialized = false;
.....
public void setUp() {
    if (isInitialized) {
        return;
    }
    // do the setup
    isInitialized = true;
}

2) Another approach (I have not tried this but theoretical should work) is using @BeforeAll annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM