【问题标题】:NullPointerException while running unit tests using Mockito [duplicate]使用 Mockito 运行单元测试时出现 NullPointerException [重复]
【发布时间】:2015-04-17 16:20:53
【问题描述】:

在为我的控制器运行 Mockito 单元测试时,我收到以下异常。我意识到我的dataSource 在这里为空,因此出现异常,但不知道如何解决这个问题。我正在使用 Tomcat 容器来运行此 Web 应用程序,并且数据源的 JNDI 上下文在 META-INF context.xml 中定义。请指导。

例外

-------------------------------------------------------------------------------
Test set: com.study.mockito.controllers.ProductControllerTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.28 sec <<< FAILURE!
testProcessRequest(com.study.mockito.controllers.ProductControllerTest)  Time elapsed: 0.25 sec  <<< ERROR!
java.lang.NullPointerException
    at com.study.mockito.dao.MasterDao.getProduct(MasterDao.java:21)
    at com.study.mockito.service.ProductService.getProduct(ProductService.java:21)
    at com.study.mockito.controllers.ProductController.processRequest(ProductController.java:37)
    at com.study.mockito.controllers.ProductController.doGet(ProductController.java:25)
    at com.study.mockito.controllers.ProductControllerTest.testProcessRequest(ProductControllerTest.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

ProductControllerTest.java

public class ProductControllerTest {

        private HttpServletRequest request;
        private HttpServletResponse response;
        private ProductController controller;
        private RequestDispatcher rd;
        private ServletContext appContext;
        private ProductService productService;
        private Product product;

        @Before
        public void setUp() {
            controller = new ProductController();
            request = mock(HttpServletRequest.class);
            response = mock(HttpServletResponse.class);
            rd = mock(RequestDispatcher.class);
            appContext = mock(ServletContext.class);
            productService = mock(ProductService.class);
            product = mock(Product.class);
        }

        @Test
        public void testProcessRequest() throws ServletException, IOException {
            when(productService.getProduct(anyInt())).thenReturn(product);

            when(request.getServletContext()).thenReturn(appContext);
            when(appContext.getRequestDispatcher(anyString())).thenReturn(rd);


            //make an actual call
            controller.doGet(request, response);

            //verify that the method is getting called
            verify(rd).forward(request, response);
        }
    }

ProductController.java

@WebServlet(name = "ProductController", urlPatterns = {"/product.htm"})
public class ProductController extends HttpServlet {

    private static final int PRODUCT_ID = 301;

    @Resource(name = "jdbc/istore-db")
    protected DataSource dataSource;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Into the ProductController...");

        //fetch the product from the db based on productId parameter
        Product product = new ProductService(dataSource).getProduct(PRODUCT_ID);
        request.setAttribute("product", product);

        RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/jsp/product.jsp");
        rd.forward(request, response);
    }

}

【问题讨论】:

  • 代码太多。制作 SSCCE。
  • @Boris:什么是 SSCCE?
  • 你在哪里以及如何嘲笑new ProductService(dataSource)
  • SSCCE 是一个“简短、独立、正确(可编译)的示例”。有关详细信息,请参阅链接。
  • @SMA - when(productService.getProduct(anyInt())).thenReturn(product);

标签: java unit-testing nullpointerexception mockito jndi


【解决方案1】:

您正在尝试模拟 ProductService,但是当您的控制器调用 ProductService.getProduct(int) 时,它正在创建自己的新实例。您需要将 ProductService 设为类变量并将模拟的 ProductService 传递给控制器​​方法进行测试。

您可以在控制器类中为数据源添加一个 setter 方法,并以这种方式传递一个模拟数据源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 2016-06-07
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    相关资源
    最近更新 更多