使用弹簧

时间:2017-04-17 17:14:27

标签: spring rest unit-testing mockmvc

我使用spring boot编写了一个非常小的REST应用程序。

我想为身份验证编写单元测试,但即使我将@MockWithUser添加到测试中,也会收到401错误。

重要文件是

安全配置

@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)     在org.springframework.test.web.servlet.result.StatusResultMatchers $ 10.match(StatusResultMatchers.java:664)     在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)     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)     在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)     在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)     在org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)     在org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)     在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)     在org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)     在org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)     在org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(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)     在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)     在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     在org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)     在org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)     在org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)     在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)     在org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)     在org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)     at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)     在org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)     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)     在org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)     在org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)     在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)     在org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)     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)     在org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)     在org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)     在org.gradle.internal.remote.internal.hub.MessageHub $ Handler.run(MessageHub.java:377)     at org.gradle.internal.concurrent.ExecutorPolicy $ CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)     at org.gradle.internal.concurrent.StoppableExecutorImpl $ 1.run(StoppableExecutorImpl.java:40)     在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)     在java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:4)

仅使用addFilters不足以构建安全上下文。以下是一些解决方案:

在您的设置方法中,替换

$ otool -L myapp
    /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 307.5.0)
    /usr/lib/libsqlite3.dylib (compatibility version 9.0.0, current version 254.6.0)
    /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.8)
    /System/Library/Frameworks/AVFoundation.framework/AVFoundation (compatibility version 1.0.0, current version 2.0.0)
    /System/Library/Frameworks/AddressBook.framework/AddressBook (compatibility version 1.0.0, current version 30.0.0)
    /System/Library/Frameworks/AssetsLibrary.framework/AssetsLibrary (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox (compatibility version 1.0.0, current version 492.0.0)
    /System/Library/Frameworks/CoreData.framework/CoreData (compatibility version 1.0.0, current version 754.2.0)
    /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation (compatibility version 150.0.0, current version 1349.55.0)
    /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics (compatibility version 64.0.0, current version 1070.22.0)
    /System/Library/Frameworks/CoreLocation.framework/CoreLocation (compatibility version 1.0.0, current version 2101.0.62)
    /System/Library/Frameworks/CoreMedia.framework/CoreMedia (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/CoreMotion.framework/CoreMotion (compatibility version 1.0.0, current version 2101.0.62)
    /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony (compatibility version 1.0.0, current version 0.0.0)
    /System/Library/Frameworks/CoreVideo.framework/CoreVideo (compatibility version 1.2.0, current version 1.5.0)
    /System/Library/Frameworks/GLKit.framework/GLKit (compatibility version 1.0.0, current version 87.0.0)
    /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/MessageUI.framework/MessageUI (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices (compatibility version 1.0.0, current version 775.2.37)
    /System/Library/Frameworks/OpenGLES.framework/OpenGLES (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/StoreKit.framework/StoreKit (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration (compatibility version 1.0.0, current version 888.50.20)
    /System/Library/Frameworks/AdSupport.framework/AdSupport (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore (compatibility version 1.0.0, current version 603.1.30)
    /System/Library/Frameworks/SafariServices.framework/SafariServices (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/WebKit.framework/WebKit (compatibility version 1.0.0, current version 603.1.30)
    /System/Library/Frameworks/ImageIO.framework/ImageIO (compatibility version 1.0.0, current version 0.0.0)
    /System/Library/Frameworks/UIKit.framework/UIKit (compatibility version 1.0.0, current version 3600.7.47)
    /System/Library/Frameworks/Accelerate.framework/Accelerate (compatibility version 1.0.0, current version 4.0.0)
    /System/Library/Frameworks/QuartzCore.framework/QuartzCore (compatibility version 1.2.0, current version 1.11.0)
    /usr/lib/libbz2.1.0.dylib (compatibility version 1.0.0, current version 1.0.5)
    /System/Library/Frameworks/Foundation.framework/Foundation (compatibility version 300.0.0, current version 1349.54.0)
    /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.50.2)
    /System/Library/Frameworks/CFNetwork.framework/CFNetwork (compatibility version 1.0.0, current version 811.4.18)
    /System/Library/Frameworks/Security.framework/Security (compatibility version 1.0.0, current version 0.0.0)

.addFilters(springSecurityFilterChain)

来自

.apply(springSecurity())

仅此一项就可以解决测试失败问题。这仍然会让你看起来很讨厌,可以使用WebMvcTest清理很多。以下是使用WebMvcTest的更简洁的测试版本。

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