在groovy中模拟扩展的java类

时间:2014-01-23 18:14:32

标签: java unit-testing groovy mocking

如何在groovy测试中模拟由groovy(输入/输出流)扩展的java类?我尝试过mockito和groovy嘲笑,但没有运气。它有什么办法可以运作吗?任何可以处理这种情况的java / groovy库?

下面有一个groovy servlet,它在InputStream上使用groovy getText方法,在OutputStream上使用setBytes。如何在groovy测试中模拟(1)getText并验证(2)setBytes?

感谢您的帮助,

米甲

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@groovy.transform.TypeChecked
class SomeServlet extends javax.servlet.http.HttpServlet {

    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) {
        final String charset = request.getCharacterEncoding();
        final String requestPayload = request.getInputStream().getText(charset); // GROOVY getText
        response.setContentType(request.getContentType());
        response.setStatus(200);
        response.setCharacterEncoding(charset);
        response.getOutputStream().setBytes(requestPayload.getBytes(charset)) // GROOVY setBytes
    }
}


class SomeServletTest {
    @org.testng.annotations.Test
    void aTest() {
        // given
        HttpServletRequest request = mock(HttpServletRequest)
        when(request.getCharacterEncoding()).thenReturn("UTF-8")
        when(request.getInputStream().getText("UTF-8")).thenReturn("some text")  // (1)

        HttpServletResponse response = mock(HttpServletResponse)

        def ss = new SomeServlet()

        // when
        ss.doPost(request, request)

        // then
        verify(response.getOutputStream()).setBytes("some text") // (2)
    }
}

1 个答案:

答案 0 :(得分:0)

我建议您使用现成的HttpServletRequest和HttpServletResponse模拟,而不是自己模拟类。模拟Servlet API类很困难,并且在现实世界的场景中证明成本太高。

Spring Framework拥有一切: http://docs.spring.io/spring-framework/docs/3.2.x/javadoc-api/org/springframework/mock/web/package-summary.html

使用MockHttpServletRequest和MockHttpServletResponse类,单元测试非常简单易读:

import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.testng.Assert
import org.testng.annotations.Test

class SomeServletTest {

    @Test
    void aTest() {
        def request = new MockHttpServletRequest(
                characterEncoding: "UTF-8",
                content: "some text".bytes)

        def response = new MockHttpServletResponse()

        def ss = new SomeServlet()
        ss.doPost(request, response)

        Assert.assertEquals(response.getContentAsString(), "some text")
    }
}

即使您不想使用Spring Framework构建整个应用程序,您仍然可以从其出色的单元测试支持中受益。