user8556830
user8556830

Reputation: 31

Spring Test Junit 5 & Security boot 2.2 How to mock authentication?

I want to create JUnit 5 test for Rest API which uses JWT token validation: This jwt token is getting generated on The UI from different(Authentication server) and this token i am using in my API to protect how can i mock this in my Test classes. The RestController is annotated with @PreAuthorize("isAuthenticated()")

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("local")
class ManagementSoftwareControllerTest {

   
    
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    void init() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    }

    @Test
    public void testGetWidgetsSuccess() throws Exception {
   
        // Execute the GET request
        mockMvc.perform(MockMvcRequestBuilders.get("/vcf/v1/test")
                .with(csrf())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();


    }

}

Upvotes: 3

Views: 6451

Answers (1)

Amit kumar
Amit kumar

Reputation: 2724

Add below dependency :

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

And use WithMockUser as below :

@Test
@WithMockUser(username = "YourUsername", password = "YourPassword", roles = "USER")
public void testAuth() throws Exception {
    mockMvc.perform(get("/yourApi"))
        .andExpect(status().isOk());
}

Upvotes: 3

Related Questions