spring-boot - 无法调用“”,因为此服务层在 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.
}
有什么想法吗?
解决方案
推荐阅读
- tableau-api - 使用 Tableau Reader 单击 Tableau 按钮时如何隐藏下拉菜单
- mysql - phpmyadmin 中缺少 DB 图标是否等于损坏的数据库?
- python - Python 字典列表递增错误
- javascript - Vaadin 的“AbstractJavaScriptComponent”的 JavaScript 范围
- java - Apache2代理后面的专用Tomcat后面的Spring-boot?
- c# - 如何从(wpf)RichTextBox中的Run对象显示工具提示/上下文菜单
- haskell - Haskell 应用程序中的(地址边界错误)
- python - OpenCV 全景图:TypeError:无法解压不可迭代的 NoneType 对象
- android - html5画布问题,在原生WebView中反应原生
- vhdl - VHDL - 寄存器文件数据并不总是写入