我有一个@SessionScope
bean,可以跟踪当前用户的角色。当我运行应用程序时,值存在,但是当我运行集成测试时,bean为null。
这就是我所拥有的:
@Component
@SessionScope
public UserSessionDataImpl implements UserSessionData {
private String role; // "Admin" or "User"
// getters/setters below
}
//服务
@Service("roleService")
public RoleServiceImpl implements RoleService {
@Autowired
UserSessionData sessionData;
public String getRole(){
return this.sessionData.getRole();
}
public String setRole(String role){
return this.sessionData.setRole(role);
}
}
// API
@Api
public class TicketApi {
@Autowired
private RoleService roleService;
@Autowired
private TicketService TicketService;
@RequestMapping(value = "person/{id}/tickets", method = RequestMethod.GET)
public String getTickets(long personId) {
// only admins can lookup tickets
if(roleService.getRoles.equals("Admin"){
// do logic
}
}
}
//单元测试方法
@Before
public void setup(){
roleService.setRole("Admin"); //set role to admin for testing
}
@Test
// Calls TicketApi
public void getTicketsTest(){
mockMvc.perform(
get("/person/{id}/tickets")); // blows up due to null role
}
我很难过为什么roleSerivce
失去对sessionData
的引用。我确实看到UserSessionDataImpl
确实被多次实例化,我认为这不会发生。我想知道mockMvc调用是否会创建一个新的Session会导致额外的实例化。有没有其他人想出这个问题?