java - 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);
}
}
解决方案
将此依赖声明添加到测试用例
@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();
推荐阅读
- php - Doctrine2 加载实体摘要?
- html - 如何在没有任何框架的情况下将 div 左右对齐 HTML/CSS
- python - 如何让不和谐机器人使用 discord.py 向消息添加表情符号反应?
- tableau-api - 如何使用名称的外部源重命名 tableau-prep 中的列?
- django - 在基于类的视图中删除视图后重定向到项目页面
- sql - 为子查询优化 Postgresql 查询
- android - 用于组合 where、oder by 和 union all 的 SQLite 查询
- r - R dplyr:创建面板数据的计数
- angular - HttpClient.get 没有重载匹配这个调用
- python - 使用 ElementTree Python 提取不在 XML 文件中每个元素中的子元素