从测试类null

时间:2018-10-19 16:56:39

标签: java spring-boot

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

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

当我使用@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()调用中显示空指针。

1 个答案:

答案 0 :(得分: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>
相关问题