java - api测试期间的SpringBoot Nullpointer异常
问题描述
我正在尝试为我的休息控制器编写测试,并NullPointerException
在我尝试对MockMvc
实例执行操作时得到一个。
我的项目结构如下:
POJO:
@Entity
public class Pair {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String a;
private String b;
//getters and setters...
}
休息控制器:
@RestController
public class PairController {
@Autowired
private PairServiceImpl pairService;
@RequestMapping(value = "/pair", method = RequestMethod.POST)
public Pair addPair(String a, String b) {
Pair newPair = new Pair();
newPair.setA(a);
newPair.setB(b);
return pairService.addNewPair(newPair);
}
@RequestMapping(value = "/pair", method = RequestMethod.GET)
public List<Pair> getPairs() {
return pairService.getPairs();
}
}
服务层:
@Service
public class PairServiceImpl implements PairService {
@Autowired
private PairRepositoryImpl pairRepository;
public Pair addNewPair(Pair newPair) {
return pairRepository.save(newPair);
}
public List<Pair> getPairs() {
return pairRepository.findAll();
}
}
存储库:
public interface PairRepositoryImpl extends JpaRepository<Pair, Long> {
}
我想测试 PairController API 端点:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class, DatabaseConfig.class})
@AutoConfigureMockMvc
@ContextConfiguration(classes = {PairController.class})
public class PairControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private PairService pairService;
@Test
public void addPairTest() {
Pair testPair = new Pair();
testPair.setA("a");
testPair.setB("b");
ObjectMapper objectMapper = new ObjectMapper();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/pair").accept(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(testPair))).andReturn();
//The line above throws an exception
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
}
}
如果我不添加@ContextConfiguration
测试无法找到我的端点。我试图在addPair
调用该方法时记录 a 和 b 值,并且两个值都是null
. 您还可以看到我添加了一个自定义数据库配置类“ DatabaseConfig
”,其中包含一个 H2 嵌入式数据库数据源方法,因此测试不使用生产数据库。@EnableJpaRepositories
注释存在于此类中,它指向上面显示的存储库。
我试图处理许多不同的注释,但它们都有相同的最终结果:控制器方法中的 null 值。
我还尝试MockMvc
使用 WebApplicationContext 手动构造实例,并使用它在带有注释的方法@Autowired
中初始化实例- 但最终结果是相同的。MockMvc
@Before
我在类中引发异常的行下方发表了评论PairControllerTests
。
因此,如果我运行该应用程序并使用 Postman 和生产数据库对其进行测试,则端点可以正常工作,并且可以正确保存和检索数据。此问题仅在测试期间发生。
解决方案
推荐阅读
- python - 事件编码键盘输入
- python - 在后端实现 facebook 类型更简单的“喜欢”功能
- r - R:当两个事件(列)都为真时,参考其中一个来决定值
- rstudio - 删除 R studio 中的第一行错误的维度数不正确
- java - 在我用 Java 杀死它的持有者后,一个对象还活着吗?
- angular-cli - 运行“ng update”的任何变体都会触发此错误:“connect ETIMEDOUT 104.18.97.96:443”
- ruby-on-rails - Rails 5、Nginx、Puma、Rails 管理员 - ERR_TOO_MANY_REDIRECTS
- c++ - 通过 QML 仿函数对 C++ 模型进行排序和过滤?
- c# - 使用 eBUS SDK 和 EmguCV 在 C# 中从 PvBuffer 创建一个 Mat
- c - C API 应该返回值还是错误代码?