如何在 Mockito 中模拟 Cutom 注释或任何注释

问题描述

我有一个类似这样的控制器方法

@GetMapping
    @JsonView(View.IAm.class)
    public User myProfile(@CurrentUser User user) throws ResourceNotFoundException {
        if(user == null) throw new ResourceNotFoundException("Undefined User");
        return userRepository.findById(user.getId()).orElseThrow(ResourceNotFoundException::new);
    }

@CurrentUser 基本上是一个自定义注释,定义如下:

@Target({ElementType.ParaMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}

这是我的控制器测试用例:

@test()
    public void myProfile_return200() throws UnsupportedEncodingException,Exception {
        User user = new User();
        user.setId("1");

        when(mockUserRepository.findById(eq("1"))).thenReturn(Optional.of(user));

        mockedMvc.perform(get("/api/user").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
                .andReturn().getResponse().getContentAsstring();

    }

包括存储库和服务类在内的所有内容都被正确模拟,但我总是为@CurrentUser 获取空值。

知道我需要做什么来模拟自定义带注释的参数或任何带注释的参数。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)