简体   繁体   English

如何使用Junit和Mockito对REST控制器进行单元测试?

[英]How do I unit test my REST Controller using Junit and Mockito?

I have written a simple method in my controller as part of my Java Spring Boot Application which works without issue using and I have tested it using Postman. 我已经在我的控制器中编写了一个简单的方法,作为Java Spring Boot应用程序的一部分,该方法在使用时不会出现问题,并且已经使用Postman对其进行了测试。 However I am unsure how to unit test this using Junit and Mockito. 但是我不确定如何使用Junit和Mockito对它进行单元测试。 I have shown a snippet of my code below, first is my Controller.java class and then my test is within a ControllerTest.java. 我在下面显示了我的代码的片段,首先是我的Controller.java类,然后我的测试在ControllerTest.java中。 How can I unit test this correctly? 如何正确进行单元测试?

EDIT: I know my test case is the problem, I have removed it as all comments are focusing on why it is wrong. 编辑:我知道我的测试用例是问题,我已将其删除,因为所有注释都集中在错误的原因上。 I am asking how do I write a unit test case for this specific saveCase method. 我在问如何为这种特定的saveCase方法编写单元测试用例。

I have already tried looking at examples from below links Rest Controller Unit Test Spring RestController + Junit Testing 我已经尝试从下面的链接中查看示例休息控制器单元测试 Spring RestController + Junit Testing

@Autowired
Service service;

@PostMapping("/savecase")
public ResponseEntity<PIECase> saveCase(@Valid @RequestBody PIECase pieCase) {
    return ResponseEntity.ok(pieService.saveCase(pieCase));
}

You need to Mock all service which is calling inside your Restcontroller so will not get Nullpointer exception 您需要模拟在Restcontroller内部调用的所有服务,因此不会出现Nullpointer异常

RunWith(MockitoJUnitRunner.class) declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization RunWith(MockitoJUnitRunner.class)声明,它将导致@Mock和@InjectMocks批注无需任何显式初始化即可自动工作

 package com.khan.vaquar.controller;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;


@RunWith(MockitoJUnitRunner.class)
public class RestControllerTest {

    private static Logger log = Logger.getLogger(RestControllerTest.class.getName());

    @InjectMocks
    private RestController restController;


    @Mock
    private RestServiceImpl restServiceImpl;

    @Mock
    private RestResponseBuilder restResponseBuilder;

    @Mock
    private HttpServletRequest request;

    @Autowired
    RuleEngine ruleEngine;

     @Test
    public void testRestControllereFlow() throws Exception {


        String inputJson="{  \r\n" + 
                "   \"Data\":{  \r\n" + 
                "      \"personalInfo\":{  \r\n" + 
                "         \"User\":{  \r\n" + 
                "           \"email\":\"vaquar.khan@gmail.com\",\r\n" + 
                "           \"name\": \"vaquar khan\"\r\n" + 
                "          
                "        , }}+ 
                "}";
        Response response =null;
        try {
            response=restController.restControllerMethd(inputJson);
            }catch(Exception e){
        //      e.printStackTrace();
            }
        assertNotNull(response);

    }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM