DB H2和控制器的集成测试

时间:2018-06-12 06:24:37

标签: java testing integration-testing h2

我的程序中有两个集成测试,不幸的是两个都没有工作。我不知道在一个案例中写这两个问题是个好主意,但我试试。 首先,我展示了我的数据库集成测试:

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

    @MockBean
    private TeamRepository teamRepository;

    @Autowired
    private TestEntityManager testEntityManager;

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

        Iterable<Team> teams = teamRepository.findAll();
        assertThat(teams).hasSize(2).contains(team, team2);
    }

在这个测试中,我向我的数据库中添加了2个元素,并期望这个测试没问题,但它会返回:

java.lang.AssertionError: 
Expected size:<2> but was:<0> in:
<[]>

在我的第二次测试中我想测试控制器方法显示所有元素。 这是我在cotroller中的方法:

@GetMapping("/teams")
    public List<TeamDto> findAll() {
        return teamService.findAll();
    }

我的测试方法如下: @SpringJUnitWebConfig(classes = CrewApplication.class)

public class TeamControllerMethodIntegrationTest {
    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
    at com.softwaremind.crew.people.integrationTest.TeamControllerMethodIntegrationTest.getAccount

我在一周内参加了这项测试,我真的不知道如何修复它。

1 个答案:

答案 0 :(得分:0)

在您的第一个案例中替换

@MockBean
private TeamRepository teamRepository;

@Autowired
private TeamRepository teamRepository;

(你不能使用mock并期望它从内存db中返回值)

为你进行第二次测试。删除@SpringJUnitWebConfig并使用

进行注释
@RunWith(SpringRunner.class)
@WebMvcTest()

并将自动装配添加到MockMvc

@Autowired
private MockMvc mockMvc;

编辑

另外删除setup()方法,因为应该已经配置了所有内容。 (然后你也不需要webApplicationContext属性)并断言你正在使用的测试注释是org.junit.Test(检查你的导入)