2017-04-17 190 views
1

我有一個使用彈簧引導編寫的非常小的REST應用程序。單元測試安全的彈簧休息控制器

我想寫一個單元測試的認證,但即使我添加@MockWithUser測試,我收到401錯誤。

的importent文件是

安全配置

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
    auth 
      .inMemoryAuthentication() 
      .withUser("user").password("password").roles("USER"); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .csrf().disable() 
      .authorizeRequests() 
      .antMatchers("/**") 
      .hasRole("USER") 
      .anyRequest() 
      .permitAll() 
      .and() 
      .anonymous().disable() 
      .exceptionHandling() 
      .authenticationEntryPoint(new org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint("headerValue")); 
} 

的MainApp與控制器

@Controller 
@RequestMapping("/test") 
@ComponentScan 
@SpringBootApplication 
public class MainApp { 


@RequestMapping(method= RequestMethod.GET) 
public @ResponseBody String sample(){ 

    return "Test"; 
} 

public static void main(String[] args) throws Exception { 
    SpringApplication.run(MainApp.class, args); 
} 
} 

最後測試(這是不工作)

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = MainApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
public class AuthenticationTest { 

@Autowired 
private TestRestTemplate testRestTemplate; 

@Autowired 
private WebApplicationContext context; 

@Autowired 
private Filter springSecurityFilterChain; 

private MockMvc mvc; 

@LocalServerPort 
private int port; 

@Before 
public void setup() { 
    mvc = MockMvcBuilders 
      .webAppContextSetup(context) 
      .addFilters(springSecurityFilterChain) 
      .build(); 
} 

@Test 
@WithMockUser(username="admin",roles={"USER","ADMIN"}) 
public void shouldReturn200WhenSendingRequestToControllerWithRoleUser() throws Exception { 
    then(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()); 
    mvc.perform(get("/test")).andExpect(status().isOk()); 

} 

@Test 
@WithMockUser(username="admin",roles={"USER","ADMIN"}) 
public void shouldAuthenticatedBeTrueWithRoleUser() throws Exception { 
    then(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()); 
} 
} 

正如你所看到的,有兩個測試用例。第二個通過,第一個不是(接收401,不是200響應代碼,下面的堆棧跟蹤)。

你能告訴我一個可以正確測試身份驗證嗎?

java.lang.AssertionError:狀態預期:< 200>但:< 401> 在org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54) 在org.springframework.test。 util.AssertionErrors.assertEquals(AssertionErrors.java:81) at org.springframework.test.web.servlet.result.StatusResultMatchers $ 10.match(StatusResultMatchers.java:664) at org.springframework.test.web.servlet.MockMvc $ 1.andExpect(MockMvc.java:171) at graphEndpoint.dataConnection.controller.AuthenticationTest.shouldReturn200WhenSendingRequestToControllerWithRoleUser(AuthenticationTest.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:498)在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50) .model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate (RunBefores.java:26) at org.springframework.test.context.junit4.statements.Run BeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat。評價(SpringRepeat.java:84) 在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) 在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) 在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290) 1 org.junit.runners.ParentRunner $。日程表(ParentRunner.java:71) at org.junit.runners.Pa在org.junit.runners.ParentRunner.access $ rentrunner.runChildren(ParentRunner.java:288) $ 000(ParentRunner.java:58) at org.junit.runners.ParentRunner $ 2。評估(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate( RunAfterTestClassCallbacks.java:70) 在org.junit.runners.ParentRunner.run(ParentRunner.java:363) 在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) 的組織。 gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass在(JUnitTestClassExecuter.java:114) 在org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57) org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUN itTestClassProcessor.java:66) 在org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) 在sun.reflect.NativeMethodAccessorImpl .invoke(NativeMethodAccessorImpl.java:62) 在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:498) 在org.gradle.internal .dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java :32) at org.gradle.internal.dispatch.ProxyDispatchAdapter $ DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy。$ Proxy3.processTestClass(Unknown Source) at org.gradle.api.internal.tasks。 testing.worker.TestWorker.processTestClass(TestWorker.java:109) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在sun.reflect.DelegatingMethodAccessorImpl .invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org .gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.jav a:24) at org.gradle.internal.remote.internal.hub.MessageHub $ Handler.run(MessageHub.java:377) at org.gradle.internal.concurrent.ExecutorPolicy $ CatchAndRecordFailures.onExecute(ExecutorPolicy.java: 54) 在org.gradle.internal.concurrent.StoppableExecutorImpl $ 1.run(StoppableExecutorImpl.java:40) 在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 在java.util.concurrent.ThreadPoolExecutor中$ Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)

回答

1

簡單地使用addFilters不足以構建安全上下文。這裏有幾個解決方案:

在你的設置方法與

.apply(springSecurity()) 

org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; 

更換

.addFilters(springSecurityFilterChain) 

這本身就應該可以解決測試失敗。這仍然讓你看到一個討厭的類,可以通過使用WebMvcTest清理很多。使用WebMvcTest,這是一個更簡潔的測試版本。

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 
import org.springframework.security.test.context.support.WithMockUser; 
import org.springframework.test.context.junit4.SpringRunner; 
import org.springframework.test.web.servlet.MockMvc; 

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 

@RunWith(SpringRunner.class) 
@WebMvcTest(controllers = MainApp.class) 
public class AuthenticationTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @Test 
    @WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) 
    public void shouldReturn200WhenSendingRequestToControllerWithRoleUser() throws Exception { 
     mockMvc.perform(get("/test")).andExpect(status().isOk()); 
    } 
} 
+0

是的,看起來方式更好。我對春天來說很新(基本上在過去的幾年中,除了硒測試之外,還沒有使用過很多java),所以我還不知道所有這些智能註釋。稍後我會嘗試此代碼(在此計算機上沒有IDE)。非常感謝你! – AsconX

+0

我現在得到以下異常:「java.lang.IllegalStateException:無法加載ApplicationContext」一些研究告訴我爲上下文創建一個xml文件。但是應用程序本身沒有這樣做。我是否真的需要將該文件添加到項目中才用於測試,還是有另一個我可能使用的智能註釋? :) – AsconX

+0

到目前爲止,我嘗試了什麼(沒有改變任何東西):添加@ContextConfiguration(classes = MainApp.class)並添加@SpringBootTest(...)不起作用,因爲那麼有多個上下文定義。 – AsconX