title: Inject Authentication in SecurityContext for JUnit tests (Java+Spring)
body: <p>I have a test method for serivice method. Service method has the next annotation:</p>
  <pre><code>@PreAuthorize(&quot;verifyRole(T(java.util.Set).of(&quot; +
      &quot;'ROLE_HEAD_BANK', 'ROLE_OPERATOR_BANK_REPORTER', 'ROLE_AUTHORIZED_BANK_REPORTER',&quot; +
      &quot; 'ROLE_AUTHORIZED_BANK_REPORTER', 'ROLE_OPERATOR_BANK_REPORTER'))&quot;)
  </code></pre>
  <p>Method verifyRole:</p>
  <pre class="lang-java prettyprint-override"><code>public boolean verifyRole(Set&lt;String&gt; roles) {
    var grantedAuthorities =
      ((User) authentication.getPrincipal()).getGrantedAuthorities()
      .stream()
      .map(GrantedAuthority::getAuthority)
      .collect(Collectors.toSet());
  
    return !Collections.disjoint(grantedAuthorities, roles);
  }
  </code></pre>
  <p>I try to run my test method with <code>@WithMockUser(roles = {&quot;HEAD_BANK&quot;,&quot;AUTHORIZED_BANK_REPORTER&quot;})</code> and it fails in verifyRole method on <code>(User) authentication.getPrincipal()</code> with the next error:
  <code>java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.kilma.raw.domain.entity.User (org.springframework.security.core.userdetails.User and com.kilma.raw.domain.entity.User are in unnamed module of loader 'app')</code></p>
  <p>I've tried different type of solving that moment and @WithMockUser the farest I could go. If there any other way to handle it please tell me? Maybe I need to work on SecurityContext but already tried and didn't work.</p>
  <p>P.S. When I comment @PreAuthorize annotation everything works well.</p>
  <p>My test code that fails on reportService.getReport, getReport method with @PreAuthorize annotation:</p>
  <pre class="lang-java prettyprint-override"><code>@Test
  @WithMockUser(roles = {
    &quot;HEAD_BANK&quot;,
    &quot;AUTHORIZED_BANK_REPORTER&quot;
  })
  void getReport_success() {
    final ReportResponse report = reportService.getReport(1 L, bank1MockedAuth).getPayload();
  
    final long publishedWithDataReportId = 1 L;
    assertEquals(publishedWithDataReportId, report.getId());
    final Instant instant = Instant.parse(&quot;2022-04-01T00:00:00.000Z&quot;);
    final Long testDate = instant.toEpochMilli();
    assertEquals(testDate, report.getCreatedAt());
    assertEquals(testDate, report.getModifiedAt());
    assertEquals(KEY_MORTGAGE_INDICATOR, report.getReportType());
    assertEquals(testDate, report.getReportPeriod());
    assertEquals(PUBLISHED, report.getStatus());
  }      
  </code></pre>