Created
May 1, 2024 15:24
-
-
Save sachin-handiekar/d997421f26418930ff1dea3fc78e814c to your computer and use it in GitHub Desktop.
DefaultMethodSecurityExpressionHandlerTest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Before; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.mockito.InjectMocks; | |
import org.mockito.Mock; | |
import org.mockito.junit.MockitoJUnitRunner; | |
import org.springframework.expression.spel.support.StandardEvaluationContext; | |
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; | |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import static org.junit.Assert.assertEquals; | |
import static org.mockito.Mockito.*; | |
@RunWith(MockitoJUnitRunner.class) | |
public class DefaultMethodSecurityExpressionHandlerTest { | |
@Mock | |
private MethodSecurityExpressionHandler mockExpressionHandler; | |
@InjectMocks | |
private DefaultMethodSecurityExpressionHandler defaultHandler; | |
@Before | |
public void setup() { | |
defaultHandler = new DefaultMethodSecurityExpressionHandler(); | |
defaultHandler.setExpressionHandler(mockExpressionHandler); | |
} | |
@Test | |
public void testCreatedEvaluationContextWithAuthentication() { | |
// Create a mock authentication object | |
Authentication authentication = new UsernamePasswordAuthenticationToken("username", "password"); | |
// Set the authentication object in the security context | |
SecurityContextHolder.getContext().setAuthentication(authentication); | |
// Create a mock EvaluationContext | |
StandardEvaluationContext mockEvaluationContext = mock(StandardEvaluationContext.class); | |
// Set up behavior for the mocked ExpressionHandler | |
when(mockExpressionHandler.createEvaluationContext(eq(authentication), any())) | |
.thenReturn(mockEvaluationContext); | |
// Invoke the method being tested | |
StandardEvaluationContext createdContext = defaultHandler.createEvaluationContext(); | |
// Verify that the expression handler's createEvaluationContext method was called with the correct arguments | |
verify(mockExpressionHandler, times(1)).createEvaluationContext(eq(authentication), any()); | |
// Assert that the returned context is the same as the mocked context | |
assertEquals(mockEvaluationContext, createdContext); | |
} | |
// Add more test cases as needed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment