Search code examples
spring-bootspring-securityspring-data-jpajunit5basic-authentication

Basic-auth is required but the test case passes without authentication in Spring boot Application


I added the Basic AUTH in the Spring boot application, which works perfectly fine. when I write test cases, the test case passes without authentication. I'm surprised how it is possible that the test case runs without Authentication as the application needs authentication.

import com.example.userandroles.Entities.Users;
import com.example.userandroles.Service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.Base64;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebAppConfiguration
@SpringBootTest
class UsersControllerTest {
    private MockMvc mvc;

    @Mock
    private UserService userService;

    @InjectMocks
    private UserController userController;

    private ObjectMapper om = new ObjectMapper();

    @Autowired
    WebApplicationContext context;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void addUser() throws Exception {
        Users user = new Users(1L, "Numaira", "Nawaz");
        String jsonRequest = om.writeValueAsString(user);

        MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/v1/user")
                        .content(jsonRequest)
                        .contentType(MediaType.APPLICATION_JSON)
                        .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("useddr:pass".getBytes())))
                .andExpect(status().isCreated())
                .andReturn();

        //assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
    }

    @Test
    void update() {
    }

    @Test
    public void testFindUser_Success() throws Exception {
        Long id = 1L;
        Users user = new Users(id, "Numaira", "Nawaz");

        //Mockito.when(userService.findUserById(id)).thenReturn(user);
        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/v1/user/{id}", id)
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();

        String responseBody = result.getResponse().getContentAsString();
        Users responseUser = om.readValue(responseBody, Users.class);

        assertEquals(MediaType.APPLICATION_JSON_VALUE, result.getResponse().getContentType());
        assertEquals(user.getFirstName(), responseUser.getFirstName());
    }
}

 

And the application.properties file

spring.datasource.url=jdbc:h2:mem:userandroles
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.security.user.name=user
spring.security.user.password=pass

Why does the test case run without authentication as authentication is required?


Solution

  • @BeforeEach
    void setUp() {
    MockitoAnnotations.openMocks(this);
    mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    

    I got the solution when I removed the setUp method then the authentication works properly.