【问题标题】:Why cant i import @WithMockUser to my test为什么我不能将@WithMockUser 导入我的测试
【发布时间】:2018-03-26 12:50:15
【问题描述】:

我正在尝试使用 @With Mock User 进行身份验证测试,但它拒绝在 spring boot 中导入我的测试类。这是类配置

@WebAppConfiguration
@AutoConfigureMockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminPortalApplication.class)
public class BookControllerTest {

@WithMockUser 无法导入,红色表示spring boot 无法识别,我使用了这个依赖和属性

<spring-security.version>4.0.2.RELEASE</spring-security.version>


       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

一直说无法解析符号@WithMockUser

【问题讨论】:

  • 我认为:“它拒绝导入我的测试类”意味着在您的项目的类路径中找不到 WithMockUser 类?如果是这样,您确定您的类路径中有一个 spring-security >=4 版本吗?
  • 我的意思是这个 org.springframework.security.test.context.support.WithMockUserSecurityContextFactory 根本没有导入
  • 您需要添加spring-security-test 作为测试依赖项。

标签: spring-boot


【解决方案1】:

尝试新的依赖。我刚刚用这个解决了这样的问题:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

【讨论】:

  • 删除 version,因为 Spring Boot 管理此问题,您现在有风险在拉另一个版本导致各种错误。
【解决方案2】:

为库添加导入语句:

import org.springframework.security.test.context.support.WithMockUser;

并在你的 pom 中声明一个依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

【讨论】:

  • 这无济于事,因为@WithMockUserspring-security-test 的一部分,而spring-security-test 不是任何一个启动器的一部分。
【解决方案3】:

尝试强制 gradle 刷新你的依赖:

gradle --refresh-dependencies

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 2020-12-23
    • 2018-01-12
    • 2021-11-24
    • 2020-04-24
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多