Skip to content

Instantly share code, notes, and snippets.

@ghsatpute
Created November 17, 2022 09:21
Show Gist options
  • Save ghsatpute/c6d48e6a6600d636b6ef6cb46a4009aa to your computer and use it in GitHub Desktop.
Save ghsatpute/c6d48e6a6600d636b6ef6cb46a4009aa to your computer and use it in GitHub Desktop.
Disabling security configurations in SpringBoot JUnit5 tests with custom AuthValidator
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.freshworks.marketplace.installation.entity.InstalledExtensionEntity;
import com.freshworks.marketplace.installation.repository.InstalledExtensionRepository;
import com.freshworks.marketplace.installation.repository.InstalledExtensionStateRepository;
import com.freshworks.marketplace.installation.service.InstallationService;
import com.freshworks.marketplace.installation.service.SqsService;
import com.freshworks.marketplace.security.validator.AuthValidator;
import io.micrometer.core.instrument.MeterRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;

@WebMvcTest(controllers = ControllerToTest.class)
@AutoConfigureMockMvc(addFilters=false)
class InstallationControllerTest {
    @Autowired
    private WebApplicationContext context;

    @Autowired
    private MockMvc mockMvc;
    @MockBean
  
  // This is custom auth validator
    private AuthValidator authValidator;


    @BeforeEach
    public void  setup() throws Exception {
      // This is required by custom auth validator
        when(authValidator.validate(any(), anyString()))
                .thenReturn(new UsernamePasswordAuthenticationToken(null, null, Collections.emptyList()));
    }

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        ...
        MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(getExtensionsPath))
          ....
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment