Java 将SecurityContextHolder.setContext(…)设置为模拟会传递到不同的测试类,即使使用@DirtiesContext也是如此
在我的一个测试类中,我使用:Java 将SecurityContextHolder.setContext(…)设置为模拟会传递到不同的测试类,即使使用@DirtiesContext也是如此,java,spring,spring-boot,spring-test,Java,Spring,Spring Boot,Spring Test,在我的一个测试类中,我使用: //Make a security context SecurityContext securityContext = mock( SecurityContext.class ); SecurityContextHolder.setContext( securityContext ); 然后我在上面放了一些东西 在另一个测试类中,我得到了一个失败,因为那个模拟仍然存在。我在所有的测试类上添加了@DirtiesContext,但它仍然存在。当我在第二个类中检查安全上
//Make a security context
SecurityContext securityContext = mock( SecurityContext.class );
SecurityContextHolder.setContext( securityContext );
然后我在上面放了一些东西
在另一个测试类中,我得到了一个失败,因为那个模拟仍然存在。我在所有的测试类上添加了@DirtiesContext
,但它仍然存在。当我在第二个类中检查安全上下文的类时,它说这是一个模拟
如何在类之间正确重置所有内容
第一个类的运行方式为:
@RunWith( SpringJUnit4ClassRunner.class )
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@DirtiesContext
第二点就是:
@RunWith( SpringJUnit4ClassRunner.class )
@DirtiesContext
“上下文”这个词让你感到困惑
这是两种截然不同的“语境”
@DirtiesContext
与测试ApplicationContext
相关;然而,SecurityContext
是Spring Security的一部分,与ApplicationContext
无关
因此,如果您在Spring Security的SecurityContextHolder
中设置了一个SecurityContext
,那么您的工作就是在测试完成后将其删除
后者需要您手动操作。如果您想让Spring Security的测试支持来处理一切,使用
@WithMockUser
和spring security test
中的相关测试支持,您可能会更高兴。在每个\u测试\u方法之后,在测试之后的测试中,您需要清除上下文<代码>SecurityContextHolder.clearContext。在@After
或@AfterClass
方法中说(取决于设置它的位置)@DirtiesContext
在这里没有帮助。当然。Spring安全测试支持:Spring测试支持:我指的是安全contextWell示例,您已经知道如何设置SecurityContext
,因为您在问题中发布了该代码。因此,您只需在测试完成后调用SecurityContextHolder.clearContext()
(例如,在JUnit4中的@after
方法中)。