Spring bean模拟和注意调用@ExceptionHandler注释的方法

时间:2015-11-03 14:46:15

标签: spring mockito inject

通过使用doThrow进行方法调用时,我尝试抛出一个特定的异常。然后我期望通过其超类中的一个方法来处理它,该方法注释了@ExceptionHandler。 1.我应该为我的控制器类使用Spy或Mock对象(它是一个spring bean) 2.我应该使用InjectMocks吗? 3.我应该在Spring上下文中测试,因为ExceptionHandler类属于Spring

以下是我对Controller类的粗略观点:

DefaultPageController extends SuperClass
{
    @RequestMapping(method = RequestMethod.GET)
    public String get(final Model model, final HttpServletRequest request, final HttpServletResponse response)
            throws CMSItemNotFoundException
    {....}

}

我的Controller的ParentClass(它是抽象的)

public abstract class SuperClass

{...
    @ExceptionHandler(InvalidCsrfTokenException.class)
    public String handleInvalidCsrfTokenException(final InvalidCsrfTokenException exception, final HttpServletRequest request)
    {
        request.setAttribute("message", exception.getMessage());
        LOG.error(exception.getMessage(), exception);
        return FORWARD_PREFIX + "/404";
    }
...
}

最后我的测试类:

@IntegrationTest
//@RunWith(SpringJUnit4ClassRunner.class)
public class PageRedirectOnCSRFTest
{
    @Mock
    private Model model;
    @Mock
    private HttpServletRequest request;
    @Mock
    private HttpServletResponse response;
    @Mock
    private InvalidCsrfTokenException invalidCsrfTokenException;
    @Mock
    private MissingCsrfTokenException missingCsrfTokenException;

    @InjectMocks
    @Resource
    private DefaultPageController controller;


    @Before
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
        try
        {
            doThrow(invalidCsrfTokenException).when(controller).get(model, request, response);
        }
        catch (final Exception e)
        {
        }
    }

    //private final DefaultPageController controller = Mockito.spy(new DefaultPageController());
    //  private final InvalidCsrfTokenException invalidCsrfTokenException = new InvalidCsrfTokenException(
    //          Mockito.mock(CsrfToken.class), "1234");
    // private final MissingCsrfTokenException missingCsrfTokenException = new MissingCsrfTokenException("1234");

    @Test
    public void testIfCalledHandleInvalidCsrfTokenException()
    {
        try
        {
            controller.get(model, request, response);
        }
        catch (final Exception e)
        {
            // YTODO Auto-generated catch block
            Assert.assertTrue(e instanceof InvalidCsrfTokenException);
            Mockito.verify(controller, Mockito.times(1)).handleInvalidCsrfTokenException(invalidCsrfTokenException, request);
        }

    }
}

Thx和brgs

0 个答案:

没有答案