我有一个使用spring验证器的用户验证器的书面单元测试用例。下面是类。我面临的问题是因为在spring validator的validate方法中,调用service来检查用户是否是admin。但是admin服务会引发异常。所以我用try catch块覆盖了。现在,对于单元测试用例,我收到错误。
public class UserValidator implements Validator {
@Override
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
if(user.getName() == null) {
errors.rejectValue("name", "InValid user");
}
//try catch block because adminservice throws exeption
try{
AdminUser adminUser= adminservice.CheckAdmin(user.getId);
}
Catch(Exception e){
e.printStackTrace
}
}
}
Public uservAlidatorTest(){
@before
//set up done
@test(expected= Exception.class)
public testException(){
User user= new user();
user.setId("JUNK");
mockito.when(adminservice.CheckAdmin(user.getId)).thenThrow(new Exception("Invalid user"))
BindException error = new BindException(User, "user");
UserValidator(user,error);
}
}
错误跟踪:
java.lang.AssertionError: Expected exception: java.lang.Exception
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:35)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
答案 0 :(得分:0)
在验证程序实现中,您正在吞噬任何被抛出的异常。即使您正在模拟您的服务方法以抛出异常,但它在验证程序中被吞没,并且测试中不会抛出任何异常。更换验证器中的catch块,如下所示
替换
Image
与
try{
AdminUser adminUser= adminservice.CheckAdmin(user.getId);
}
Catch(Exception e){
e.printStackTrace
}
答案 1 :(得分:0)
您正在捕获CheckAdmin调用中的每个异常,并且您的单元测试需要一个。除非它之前被抛出:
用户用户=(用户)目标;
if(user.getName()== null){ errors.rejectValue(“name”,“InValid user”); }
您永远不会得到任何异常,因此您的单元测试将始终失败。