当前位置: 首页 > 知识库问答 >
问题:

与 JUnit @PreAuthorize的测试服务方法

林国安
2023-03-14

在 Spring Boot 1.4.1 中,我想对@PreAuthorize访问受限的服务方法进行单元测试(不是集成测试)。

问题是从 Eclipse 单独启动测试时似乎没有检查@PreAuthorize(尚未尝试使用 mvn 测试)。

然后,如果我奇迹般地设法正确运行测试,我将尝试使用 StudyService 界面,而不是 impl。

这是我的测试类:

@RunWith(MockitoJUnitRunner.class)
public class TestMethodSecurity {

    private static final Long STUDY_ID = 1L;

    @Mock
    private StudyRepository studyRepository;

    @InjectMocks
    private StudyServiceImpl studyService;


    @Before
    public void setup() {
        given(studyRepository.findOne(STUDY_ID)).willReturn(ModelsUtil.createStudy());
    }


    @Test
    public void findByIdWithoutAccessRightTest() {
        Study study = studyService.findById(STUDY_ID);
    }
}

这是服务:

@Service
public class StudyServiceImpl implements StudyService {


    @Autowired
    private StudyRepository studyRepository;


    @Override
    @PreAuthorize("hasAnyRole('DOES NOT EVENT CHECK SYNTAX")
    public Study findById(final Long id) {
        return studyRepository.findOne(id);
    }

}

测试成功,即为失败。

共有3个答案

弓嘉纳
2023-03-14

这就是我让它工作的方式:

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ActiveProfiles("test")
public class StudySecurityTest {

    @Autowired
    private StudyService service;

    @MockBean
    private StudyRepository repository;

    @Test
    @WithAnonymousUser
    public void testAsAnonymous() {
        ...
    }

    @Test
    @WithMockKeycloakUser(id = LOGGED_USER_ID, username = LOGGED_USER_USERNAME, authorities = { "ROLE_USER" })
    public void testAsUser() {
        ...
    }
}

如果你在@WithMockKeycloakUserRest,问我。

澹台俊晖
2023-03-14

注释您的测试类

@RunWith(SpringRunner.class)
@ContextConfiguration

您的方法应如下所示

@Test(expected = AccessDeniedException.class)
@WithAnonymousUser
@Test
    public void findByIdWithoutAccessRightTest() {
        Study study = studyService.findById(STUDY_ID);
    }

如果不至少加载安全上下文,则无法测试安全性。

您可能需要查看此示例:

public ApplicationUser getApplicationUser() {
    ApplicationUser applicationUser = (ApplicationUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return applicationUser;
}

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import com.arpit.security.user.ApplicationUser;

public class BaseTest {

    @Before
    public void setupMock() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void mockApplicationUser() {
        ApplicationUser applicationUser = mock(ApplicationUser.class);
        Authentication authentication = mock(Authentication.class);
        SecurityContext securityContext = mock(SecurityContext.class);
        when(securityContext.getAuthentication()).thenReturn(authentication);
        SecurityContextHolder.setContext(securityContext);
        when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser);
    }

}

取自: https://www.javacodegeeks.com/2017/05/mocking-spring-security-context-unit-testing.html

我想你的服务方法故意有语法错误?(缺少括号和错误的引号?

沙靖琪
2023-03-14

如果你想测试Spring Security注释,你需要使用SpringRunner,它将创建Spring Context并将Spring Security代码注入代理类。

如何测试 Spring 安全性,你可以在这里找到。

 类似资料:
  • 问题内容: 我有一个春季服务: 我为此进行了集成测试: 这是问题所在: 正如用和注释的 因为坚持语义 该线程将呼叫分叉到自己的工作线程,然后直接继续执行,以前的工作线程完成其工作可能之前。 如何在验证结果之前等待的完成?注意,如何使用Spring4和批注编写单元测试以验证异步行为_ 的解决方案?不要在这里申请,作为回报,而不是。 问题答案: 为了遵守语义,某些活动类将具有注释,例如 为了解决我的问

  • 我正在尝试从spring启动应用程序中的服务执行JUnit4测试,并且我一直使用init获取entityManagerFactory。 我还希望使用我的应用程序连接。属性文件,但它希望使用嵌入式hsqldb进行连接。 有人能给我指出正确的方向吗? 以下是相关代码: 应用特性: 主要内容: 实体: DAO/存储库: 服务: 测试: 本应包括以下内容: 堆叠:

  • 问题内容: 我想直接通过HTTP测试我的RESTful应用程序,我正在寻找可以帮助我完成该任务的工具。基本上,我正在寻找一个HTTP请求的简单包装,该请求可以提交例如HTML表单或序列化资源(如JSON或XML)。 如果有一种方法可以验证服务是否确实遵循REST体系结构准则(无状态,URI,内容协商等),那将是很好的。 能够与JUnit一起使用将是一个方便的好处。您是否知道任何可以帮助我完成我想做

  • 问题内容: 我已经使用过JUnit,但是某些测试存在一些问题,这些测试在Spring bean内具有@Autowired批注,当我引用它们时,@ Autowired的bean始终为NULL。 这是示例代码: 当调用Manager对象时,Spring会生成代理,但是当访问@Autowired parameterManager时,该对象为null,并且由于这个问题,我无法测试此方法。 知道是什么原因造

  • 我使用JUnit,但有些测试有一些问题,这些测试在Spring bean中有@Autowired注释,当我引用它们时,@Autowired的bean总是为空。

  • 我正在使用JUnit测试一个DAO类,我得到了一个nullpointerexception,我不知道为什么要启动服务类。以下是测试类: 以下是UserDaoImpl 如何在测试类中注入类?我想nullpointerxeception的原因是dao类没有正确地注入到测试类中

  • 大家好,我需要为我的方法编写单元测试。我有点麻烦,因为我是JUnit的新手。我需要为这个方法写一个测试。这是我的方法 我试过了,但我被挡了,这是我的结果 附言:测试通过了,但我不明白我的测试是不是真的

  • 问题内容: 我有一个充满void方法的Java类,我想进行一些单元测试以获得最大的代码覆盖率。 例如我有这种方法: 它的名字不好用是因为我翻译了代码以更好地理解。每种方法均会验证参数是否在某种程度上有效并且编写正确。 范例: 我的单元测试很好地涵盖了小的方法,因为我要求它们检查ErrorFile是否包含错误消息,但是我看不到如何测试方法checkIfValidElements,它什么也不返回或什么