RESTful Web服务的集成测试

时间:2018-06-08 13:45:58

标签: java integration-testing h2

这是我的集成测试控制器类。方法得到所有团队,编译时出现问题:

@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 adn创建测试我有问题因为在向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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

@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();