有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

DB H2和控制器的java集成测试

我的程序中有两个集成测试,不幸的是两个都不起作用。我不知道把这两个问题都写在一个案例中是个好主意,但我尝试了。 首先,我展示了我的db集成测试:

@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(class=crewaApplication.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) 个答案

  1. # 1 楼答案

    在第一种情况下,替换

    @MockBean
    private TeamRepository teamRepository;
    

    @Autowired
    private TeamRepository teamRepository;
    

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

    给你第二次测试。删除@SpringJUnitWebConfig并用

    @RunWith(SpringRunner.class)
    @WebMvcTest()
    

    并将Autowired添加到MockMvc

    @Autowired
    private MockMvc mockMvc;
    

    编辑

    另外,删除setup()方法,因为所有内容都应该已经配置好。(然后您也不需要webApplicationContext属性)并断言您使用的测试注释是org。朱尼特。测试(检查您的导入)