我使用会话注册表来维护单个会话。
代码如下:
@Component
public class AppLogout implements LogoutSuccessHandler{
@Autowired
private SessionRegistry sessionRegistry
...
List<SessionInformation> sessions = sessionRegistry.getAllSessions(auth.getPrincipal(), false)
现在,每当我试图为此编写测试用例时,我都会得到 NullPointerException
在第二行 sessionRegistry
或者不是模拟例外。
尝试过的事情:
无法在sessionregistry上执行InjectMock,因为它是一个接口
@Mock
SessionRegistry sg;
@InjectMocks
SessionRegistryImpl sgImpl
使用 @Mock
导致 NullPointerException
```
@Mock
SessionRegistry sg
Mockito.doReturn(list).when(sg).... (NullPointer on sg)
完全删除模拟,但仍然打开空指针 `sessionRegistry.getAllSessions(...)` 实际等级:
@Component
public class AppLogoutHandler implements LogoutSuccessHandler{
@Autowired
SessionRegistry sessionRegistry;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
if(authentication != null && authentication.getDetails() != null) {
removeAuthSession(authentication, sessionRegistry);
request.getSession().invalidate();
}
}
private void removeAuthSession(Authentication authentication, SessionRegistry sessionRegistry2) {
List<SessionInformation> session= sessionRegistry.getAllSessions(authentication.getPrincipal(), false); //sessionRegistry here is giving issue
if(!session.isEmpty()) {
....
}
}
}
测试类(这是最新版本,也尝试了第1,2点中提到的内容)
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppLogoutSuccessHandlerTest {
@MockBean
SessionRegistry registry;
@InjectMocks
AppLogoutHandler appLogoutHandler;
@org.junit.Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void onLogoutSuccessTest() {
//Mocked ServletRequest, Response here
Object object = new Object();
List<SessionInformation> informations = new ArrayList<SessionInformation>();
//informations.add(sessionInformation); SessionInformation is created above and passed
Mockito.doReturn(informations).when(registry).getAllSessions(object, false); //If i include this line it gives not a mock on when and if i doesn't then it is giving nullPointer on actual class
}
}
更新的测试用例(这在执行时为line->sessionregistry.getallsessions(authentication.getprincipal(),false)提供空指针)
@RunWith(MockitoJUnitRunner.class)
public class AppLogoutSuccessHandlerTest {
@Mock
SessionRegistry registry;
@InjectMocks
AppLogoutHandler appLogoutHandler;
/*
* @org.junit.Before public void setup() { MockitoAnnotations.initMocks(this); }
*/
@Test
public void onLogoutSuccessTest() {
//Mocked ServletRequest, Response here
Object object = new Object();
List<SessionInformation> informations = new ArrayList<SessionInformation>();
//informations.add(sessionInformation); SessionInformation is created above and passed
Mockito.doReturn(informations).when(registry).getAllSessions(object, false); //If i include this line it gives not a mock on when and if i doesn't then it is giving nullPointer on actual class
}
}
我试过注解 `@SpringBootTest` 没有它,就没有运气。
你能建议一下上述方法有什么问题吗。
暂无答案!
目前还没有任何答案,快来回答吧!