如何为需要当前用户的控制器编写统一测试?

时间:2019-04-01 15:18:45

标签: spring-mvc junit

我正在为从基础扩展的Spring控制器编写单元测试。在父亲的方法中,我调用了以下函数:

  protected OnCustomerUser getUser() {
    Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return (OnCustomerUser) obj;
  }

我应该如何测试?请记住,这是一个单元测试,我不需要创建spring上下文来运行它。

我正在使用JUnit 4.11

到目前为止,我最好的主意是重写该方法并返回一个虚拟用户,但是我不知道在使用@InjectMocks时如何做到这一点(在扩展测试套件时,我将不得不继续添加更多的模拟对象)

  @Mock
  HibernateCRMObjectTypeDao crmObjectTypeDao;

  @InjectMocks
  BpmProcessController bpmProcessController;

  @Mock
  HttpServletRequest request;

  @Before
  public void prepareMocks() {
    CRMObjectType bpmProcessType = new CRMObjectType();
    bpmProcessType.setObjectName("BPM_PROCESS");
    when(crmObjectTypeDao.getByClassName(BpmProcess.class.getName())).thenReturn(bpmProcessType);
  }

  @Test
  public void loadForm() throws Exception {
    bpmProcessController.loadForm(request, 23l, "load", null);

  }

0 个答案:

没有答案
相关问题