简体   繁体   English

如何在 TestNG 中使用 Spring WithMockUser 注释

[英]How to use Spring WithMockUser annotation with TestNG

I am using Spring Boot for my web app and TestNG for unit testing.我将 Spring Boot 用于我的 Web 应用程序并使用 TestNG 进行单元测试。 Following is the unit test I'm trying以下是我正在尝试的单元测试

@ContextConfiguration
public class AuthorizerTest extends AbstractTestNGSpringContextTests {

    @InjectMocks
    private Authorizer authorizer = new Authorizer();

    @Mock
    private PermissionRuleRepository permissionRuleRepository;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    @WithMockUser
    public void testCheckPermission() throws Exception {
        try {
            authorizer.checkPermission(null, PermissionLevel.Type.ACCOUNT_OTHER);
            fail();
        } catch (AccessDeniedException ade) {
            //
        }
    }
}

authorizer.checkPermission internally using SecurityContext to get the current username. authorizer.checkPermission内部使用SecurityContext来获取当前用户名。 But on debugging, the authentication object is null .但是在调试时, authentication对象为null Not sure why it is not getting populated when using WithMockUser .不知道为什么在使用WithMockUser时它没有被填充。

You can try to add the following annotation to your test class.您可以尝试将以下注释添加到您的测试类中。 This worked for me.这对我有用。

@TestExecutionListeners({WithSecurityContextTestExecutionListener.class})

An example can be found here: https://github.com/sbrannen/spring-events/blob/master/src/test/java/com/sambrannen/spring/events/SimpleScenarioTestNgTests.java一个例子可以在这里找到: https : //github.com/sbrannen/spring-events/blob/master/src/test/java/com/sambrannen/spring/events/SimpleScenarioTestNgTests.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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