首页 > 解决方案 > RESTful Web 服务的集成测试

问题描述

这是我的集成测试控制器类。方法获取所有团队并且编译出现问题:

@SpringJUnitWebConfig(classes = CrewApplication.class)
public class Team_Controller_Integration_Test {
    private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setup() throws Exception
{
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
    MockitoAnnotations.initMocks(this);
}

@Test
void getAccount() throws Exception {
    this.mockMvc.perform(get("/teams")
            .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$version").value(null))
            .andExpect(jsonPath("$name").value("Apacze"))
            .andExpect(jsonPath("$createOn").value(null))
            .andExpect(jsonPath("modifiedOn").value(null))
            .andExpect(jsonPath("$description").value("grupa programistow"))
            .andExpect(jsonPath("$city").value("Włocławek"))
            .andExpect(jsonPath("$headcount").value(null));
}

}

这是我的错误:

java.lang.NullPointerException

另一方面,我为 Db 创建测试并遇到问题,因为在将模拟元素添加到 db 后它们返回 null:

@RunWith(SpringRunner.class)
@DataJpaTest
public class Team_database_integration_test {

    @MockBean
    private TeamRepository teamRepository;

    @Autowired
    private TestEntityManager testEntityManager;

    @Test
    public void testDb(){
        Team team = new Team(1L,"teamName","teamDescription","krakow",7);
        testEntityManager.persist(team);
        testEntityManager.flush();

        System.out.println(team);
    }
}

标签: javaintegration-testingh2

解决方案


将此依赖声明添加到测试用例

@Autowired
    private WebApplicationContext webApplicationContext;

并更正初始化

@Before
    public void setup() throws Exception
    {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
        MockitoAnnotations.initMocks(this);
    }

尝试更改为此签名,我认为内容类型默认为 -json。先尝试不使用断言,然后添加断言以进行验证!

MvcResult CDTO = this.mockMvc.perform(get("/plan/1"))
        .andExpect(status().isOk())
        .andReturn();

推荐阅读