Java Junit测试中异常HashMap返回null后
在我的项目中,在DAO类中,在delete方法中,作为delete响应,我返回了一个HashMap。我用过JPA和Spring Boot。在Try-Catch中,成功删除后,映射中的“作为键”状态将被置为“作为值字符串”OK 正如我们所知,在JPA中,若主键未找到实体,则在删除时会发生异常。异常发生后,HasMap中的as键状态将被置位,as值字符串将失败 这个HashMap将由DAO delete方法返回,我的意图是在JUnit中使用它进行断言。现在的问题是:成功删除它可以正常工作,但是如果我试图删除一个不存在的实体,那么键值分配在Dao方法中工作,但是当我试图在JUnit测试方法中访问它时,它显示为null。即使我已经在delete方法中打印了HasMap,它显示了它的键值,但在Junit中,同时显示null 单元测试代码 案例2 案例3 要成功删除,消息如下所示:Java Junit测试中异常HashMap返回null后,java,spring,junit,Java,Spring,Junit,在我的项目中,在DAO类中,在delete方法中,作为delete响应,我返回了一个HashMap。我用过JPA和Spring Boot。在Try-Catch中,成功删除后,映射中的“作为键”状态将被置为“作为值字符串”OK 正如我们所知,在JPA中,若主键未找到实体,则在删除时会发生异常。异常发生后,HasMap中的as键状态将被置位,as值字符串将失败 这个HashMap将由DAO delete方法返回,我的意图是在JUnit中使用它进行断言。现在的问题是:成功删除它可以正常工作,但是如果我
response (dao) : {status=OK}
//hibernate sql show
response (test) : {status=OK}
到目前为止,我可以理解,作为异常,当试图删除一个空实体时,HasMap键值对赋值是在Dao delete方法中,但返回到测试方法
可能的原因是什么
代码完整代码可在GitHub中访问:
这是一个开源项目,欢迎您参与 您正在使用嵌套的JPA方法find and delete 如果标识符为null,find方法将引发异常
@Override
public Map<String, String> delete(String id) {
System.out.println("DAO Delete: ");
Map<String, String> response = new HashMap<>();
String s = "";
try {
ProfileBasic profileBasic = entityManager.find(ProfileBasic.class, new Long(id));
entityManager.remove(profileBasic);
s = "OK";
} catch (Exception e) {
s = "FAIL";
System.out.println("Profile Basic Delete Fail!");
// e.printStackTrace();
}
response.put("status", s);
System.out.println("response (dao) : "+ response.toString());
return response;
}
Profile Basic Delete Fail!
response (dao) : {status=FAIL}
Test Delete Fail!
response (test) : {}
@Override
public Map<String, String> delete(String id) {
System.out.println("DAO Delete: ");
Map<String, String> response = new HashMap<>();
try {
ProfileBasic profileBasic = entityManager.find(ProfileBasic.class, new Long(id));
entityManager.remove(profileBasic);
response.put("status","OK");
} catch (Exception e) {
System.out.println("Profile Basic Delete Fail!");
response.put("status","FAIL");
// e.printStackTrace();
}
System.out.println("response (dao) : "+ response.toString());
return response;
}
Profile Basic Delete Fail!
response (dao) : {status=FAIL}
Test Delete Fail!
response (test) : {}
@Override
public Map<String, String> delete(String id) {
System.out.println("DAO Delete: ");
Map<String, String> response = new HashMap<>();
ProfileBasic profileBasic=null;
try {
profileBasic = entityManager.find(ProfileBasic.class, new Long(id));
response.put("status", "OK");
} catch (Exception e) {
System.out.println("Profile Basic Delete Fail!");
response.put("status", "FAIL");
// e.printStackTrace();
}
entityManager.remove(profileBasic);
System.out.println("response (dao) : " + response.toString());
return response;
}
Profile Basic Delete Fail!
response (dao) : {status=FAIL}
Test Delete Fail!
response (test) : {}
response (dao) : {status=OK}
//hibernate sql show
response (test) : {status=OK}