LoginContextTest.java
1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.xly.erp.common.security;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class LoginContextTest {
@AfterEach
void tearDown() {
LoginContext.clear();
}
@Test
void setAndCurrent_returnsSameUser() {
LoginContext.LoginUser u = new LoginContext.LoginUser(42, "alice", "NORMAL", "HQ");
LoginContext.set(u);
assertSame(u, LoginContext.current());
}
@Test
void clear_returnsNullForCurrent() {
LoginContext.set(new LoginContext.LoginUser(1, "x", "NORMAL", "HQ"));
LoginContext.clear();
assertNull(LoginContext.current());
}
@Test
void setAndCurrent_isolatedPerThread() throws InterruptedException {
LoginContext.set(new LoginContext.LoginUser(1, "main", "NORMAL", "HQ"));
AtomicReference<LoginContext.LoginUser> seen = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(() -> {
seen.set(LoginContext.current());
LoginContext.set(new LoginContext.LoginUser(2, "child", "SUPER_ADMIN", "HQ"));
latch.countDown();
});
t.start();
latch.await();
t.join();
assertNull(seen.get(), "子线程不应继承父线程 ThreadLocal");
assertEquals("main", LoginContext.current().username(),
"父线程上下文不应被子线程改动影响");
}
}