【问题标题】:Spring 5 REST testing WebTestClient nullSpring 5 REST 测试 WebTestClient null
【发布时间】:2018-04-18 10:55:40
【问题描述】:

我正在尝试学习如何在 SpringBoot 中测试 REST。我已经从https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html 重写了代码并对其进行了一些更改以满足我的需要,但是我的testClient 变量一直为空。我试图手动实例化,例如通过使用这个:

WebTestClient testClient = WebTestClient
  .bindToServer()
  .baseUrl("http://localhost:8080")
  .build();

或通过使用 ApplicationContext 构建它:

@Autowired
private ApplicationContext context;

WebTestClient testClient = WebTestClient.bindToApplicationContext(context)
  .build();

没有任何效果,但是当我尝试使用 ApplicationContext 方式时,我的堆栈跟踪显示“需要 ApplicationContext”。

这就是我的代码现在的样子:

@AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
class BusinessProcessControllerTest {

    @Autowired
    private WebTestClient testClient;

    @Test
    public void returns_type_JSON(){
        testClient.get().uri("/businessProcess").accept(MediaType.APPLICATION_JSON);
    }

在 Spring 教程中,他们甚至没有使用 @AutoConfigureWebTestClient,但如果我没有将它添加到代码中,它就无法工作。还能缺少什么?在这个版本中,我总是得到 NullPointerException - 调试器说testClient 是空的。我怎样才能让它工作,以便进一步的测试写作成为可能?

【问题讨论】:

  • 您是否尝试过将spring-boot-starter-webflux 添加为测试依赖项?
  • 你找到解决办法了吗?
  • 很难称之为解决方案,但如果您还需要测试帮助,我已经添加了答案

标签: rest unit-testing spring-boot


【解决方案1】:

我没有解决这个问题,而是使用了其他类。我对此不是很满意,但它确实有效,所以这是我在本课程中使用的:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
public class BusinessProcessControllerTest {

    @Autowired
    private MockMvc mockMvc;

我使用MockMvc 对象来执行这样的 HTTP 方法:

@Test
    public void businessProcessSetImportanceReturns201ForExistingResource() throws Exception {
        this.mockMvc.perform(postAsAdmin("/businessProcesses/2/setImportance")).andExpect(status().isCreated());
    }

“postAsAdmin”方法是我自己的实现,下面是它的工作原理:

public static MockHttpServletRequestBuilder postAsAdmin(String urlTemplate, Object... uriVars) {
        return MockMvcRequestBuilders.post(urlTemplate, uriVars).with(httpBasic(ADMIN_USERNAME, PASSWORD));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2019-06-14
    • 2020-04-11
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多