在这种情况下不要使用mockStatic
,您将模拟整个静态类,这就是您无法调试它的原因。
而是使用其中之一来避免模拟整个静态类:
spy
PowerMockito.spy(CasSessionUtil.class) PowerMockito.when(CasSessionUtil.getCarrierId()).thenReturn(1L);
或者stub
PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "getCarrierId")).toReturn(1L);
并且stub
,如果方法有参数(例如字符串和布尔值),请执行以下操作:
PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "methodName", String.class, Boolean.class)).toReturn(1L);
这是 finla 代码,我选择使用stub
:
@RunWith(PowerMockRunner.class) // replaces the PowerMockRule rule
@PrepareForTest({ CasSessionUtil.class })
public class TestClass extends AbstractShiroTest {
@Autowired
SomeService someService;
@Before
public void setUp() {
Map<String, Object> newMap = new HashMap<String, Object>();
newMap.put("userTimeZone", "Asia/Calcutta");
Subject subjectUnderTest = mock(Subject.class);
when(subjectUnderTest.getPrincipal())
.thenReturn(LMPTestConstants.USER_NAME);
Session session = mock(Session.class);
when(session.getAttribute(LMPCoreConstants.USER_DETAILS_MAP))
.thenReturn(newMap);
when(subjectUnderTest.getSession(false))
.thenReturn(session);
setSubject(subjectUnderTest);
// instead, add the getCarrierId() as a method that should be intercepted and return another value (i.e. the value you want)
PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "getCarrierId"))
.toReturn(1L);
}
@Test
public void myTestMethod() {
someService.doSomething();
}
}