【问题标题】:SpringBoot Component autowired from Test class null从测试类 null 自动装配的 SpringBoot 组件
【发布时间】:2019-03-24 14:39:44
【问题描述】:

我有一个测试类,其中@Autowireds 有两个不同的类。其中一个是@Service,另一个是@RestController。

当我使用@Service 时,它​​工作正常。

当我使用 @RestController 时,它会抛出 NullPointerException。

它不能连接控制器有什么原因吗?我认为它可能与创建 Web 上下文有关,但我也尝试添加 SpringBootTest 和指向 MOCK(和其他)的 webEnvironment 以查看是否可以启动它。

我也尝试过 MockMvc 的东西,但我不确定它应该如何工作。

有什么方法可以轻松调用其中一个控制器来执行完整的集成测试用例吗?

@Autowired
private ThingService tservice;

@Autowired
private ThingController tconn;

@Test
public void testRunThing() {
    Thing t = new Thing(1, "Test");
    tservice.configureThing(t);
    Thing t2 = new Thing(1, "Second thing");
    tconn.getThing(t2);

    t3 = tservice.findThing(1);
    assertEqual(t3.getValue(), "Second thing");
}

tservice 函数做了一些工作,包括最终持久化到数据库(在本例中是 H2,它又通过存储库自动连接)。

tconn 函数处理更新,就像它被发送到其余端点一样(在这种情况下,它会将 ID 为 1 的“事物”更新为新的字符串值)

空指针出现在tconn.getThing() 调用中。

【问题讨论】:

  • 能否将测试类添加到问题中?
  • @Boris 我添加了一些精简示例
  • 好的,类级别的注解是什么?

标签: java spring-boot


【解决方案1】:

MockMvc 使用简单示例: 测试类

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class LoginControllerTest {

    @Autowired
    private MockMvc mockMvc;

简单测试

        @Test
        public void loginOk() throws Exception {
            this.mockMvc.perform(post("/login").param("username", "name")
                    .param("password", "1111" )).andExpect(status().isOk())
         .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
        }

如果您只想检查它是否是响应对象,您可以使用

 .andExpect(content().json("{}"));

响应的空数组

 .andExpect(content().json("[]"));

包含两个对象的数组

.andExpect(content().json("[{}, {}]"));

如果您想要确切的结果,您可以将其作为 json 字符串获取,然后对其进行解析。

 MvcResult result = this.mockMvc.perform(post("/login").param("username", "name")
                    .param("password", "1111" )).andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).andReturn();
String resultJsonString = result.getResponse().getContentAsString();

你需要一个依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

【讨论】:

  • 这只会导致this.mockMvc.performorg.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException 出现异常——这可能是无关的......
  • 它表明测试正在运行,并且当您向正在测试的其余端点发出请求时,您在应用程序的某处收到了 NullPointerException。如果您可以提供控制器方法的确切代码(带有所有注释),我将能够为您提供此端点的确切 tescase 代码,以确保正确编写测试用例。
猜你喜欢
  • 2021-01-10
  • 2016-12-17
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
相关资源
最近更新 更多