jmockit教程,使用Jmockit进行Servlet JUnit测试

I want build a unit test for a Servlet using JUnit and JMockit.

I have an ImageServlet which takes image IDs (String) as request parameters and if ID is null the servlet throws a HTTP status code 404 (not found)

for this scenario I have the test:

Unit Test:

@RunWith(JMockit.class)

public class ImageServletTest {

@Tested

private ImageServlet servlet;

@Injectable

HttpServletRequest mockHttpServletRequest;

@Injectable

HttpServletResponse mockHttpServletResponse;

@Injectable

PrintWriter printWriter;

@Injectable

ServletOutputStream servletOutputStream;

@Before

public void setUp() throws Exception {

servlet = new ImageServlet();

initMocks(null);

}

private void initMocks(final String imgId) throws Exception {

new NonStrictExpectations() {{

mockHttpServletRequest.getParameter("id");

result = imgId;

mockHttpServletResponse.getWriter();

result = printWriter;

mockHttpServletResponse.getOutputStream();

result = servletOutputStream;

}};

}

@Test

public void testImageNotFound() throws Exception {

servlet.doGet(mockHttpServletRequest, mockHttpServletResponse);

org.junit.Assert.assertTrue(mockHttpServletResponse.getStatus() == HttpServletResponse.SC_NOT_FOUND);

}

}

the problem is that my Assertion fails as mockHttpServletResponse.getStatus() always returns 0, is there a way to get the resulting Status code of the servlet using JMockit?

解决方案

I'm not familiar with all the latest JMockit injection stuff, so I used JMockits support for "fakes".

@RunWith(JMockit.class)

public class ImageServletTest3 {

@Test

public void testImageNotFound() throws Exception {

ImageServlet servlet = new ImageServlet();

servlet.doGet(

new MockUp() {

@Mock

public String getParameter(String id){

return null;

}

}.getMockInstance(),

new MockUp() {

@Mock

public void sendError(int num){

Assert.assertThat(num, IsEqual.equalTo(404));

}

}.getMockInstance()

);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值