如果我@WithMockUser在 Spring Boot 中的測驗類上有注釋,我如何才能為單個測驗覆寫/取消此設定,在該測驗中我想查看代碼在沒有設定主體的情況下如何表現?
uj5u.com熱心網友回復:
如果您想查看代碼對不同用戶的行為,您可以@WithMockUser直接在方法上放置另一個。
@SpringBootTest
@WithMockUser(username="user", password="password")
public class UserSecurityTest {
@Test
@WithMockUser(username="otherUser", password="password")
public void testMockUserOverride() {
...
}
}
如果您想查看代碼在沒有憑據的情況下如何運行,那么您需要在測驗開始時清除安全背景關系。
@SpringBootTest
@WithMockUser(username="user", password="password")
public class UserSecurityTest {
@Test
public void testNoAuth() {
SecurityContextHolder.clearContext();
...
}
}
這是一個完整的示例,其中包括在清除身份驗證后運行的測驗,以確保將其恢復到類級別模擬設定的內容。
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.test.context.support.WithMockUser;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
@WithMockUser(username = "user", password = "password")
@TestMethodOrder(MethodOrderer.class)
public class SecurityTest {
public String getCurrentUser() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(Authentication::getPrincipal)
.map(user -> ((User)user).getUsername())
.orElse("noAuth");
}
@Test
@Order(0)
public void testClassLevelMockUser() {
assertEquals("user",getCurrentUser());
}
@Test
@Order(1)
@WithMockUser(username = "otherUser")
public void testOverrideMock() {
assertEquals("otherUser", getCurrentUser());
}
@Test
@Order(2)
public void testNoAuth() {
SecurityContextHolder.clearContext();
assertEquals("noAuth", getCurrentUser());
}
@Test
@Order(3)
public void testClassLevelMockUserNotDestroyedByOtherTest() {
assertEquals("user", getCurrentUser());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513982.html
標籤:弹簧靴验证弹簧测试
上一篇:如何減少if陳述句
