首页 > 解决方案 > 无法调用“”,因为此服务层在 Cucumber 测试中为空

问题描述

我目前正在对 REST API 进行自动测试。我正在尝试使用 Cucumber,并且当我尝试在控制器上编写测试代码时。我有一个NullPointerException无法调用的时间findById,因为this.controller我的测试类为空。

这是我的代码

import helloworld.entity.LtHelloWorld;
import helloworld.entity.HelloWorld;
import helloworld.controller.HelloWorldController;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.java.sl.In;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import java.time.LocalDateTime;

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(MockitoJUnitRunner.class)
public class GETTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private HelloWorldController helloWorldController;

    private int id = 1;
    private String url = "/registrations/";

    // The given keyword is omitted in this example. 

    @When("I type in http:\\/\\/localhost:8080\\/hello\\/{int}")
    public void inURI(Integer id) throws Exception {
        System.out.println("Testing localhost:8080/registrations/" + id + "...");

        /* Mocking the expected response body
         */

        LtHelloWorld ltHelloWorld = new HelloWorld(1, "World", null, 1, 0);
        HelloWorld helloWorld = new HelloWorld (1, "Hello", ltHelloWorld);

        Mockito.when(helloWorldController.findById(1)).thenReturn(java.util.Optional.of(helloWorld));

        /* Using URL
         */
        MvcResult mvcResult = mockMvc.perform(get(url+id.toString())).andExpect(status().isOk()).andReturn();

        String actualJSONResponse = objectMapper
                .writeValueAsString(registrations);
        System.out.println(actualJSONResponse);

    }

    // The then keyword is omitted in this example. 
}

有什么想法吗?

标签: spring-bootcucumber

解决方案


推荐阅读