java.lang.exception_如何解決java.lang.AssertionError:期望的異常:Mockito中的java.lang.Exception...

我有一個使用spring驗證器的用戶驗證器的書面單元測試用例。下面是類。我在Spring驗證器的validate方法中面臨問題,調用服務來檢查用戶是否爲admin。但是管理服務會引發異常。所以我用try catch塊覆蓋。現在對於單元測試用例,我收到了錯誤。如何解決java.lang.AssertionError:期望的異常:Mockito中的java.lang.Exception

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

你想抓住哪個異常?是全部嗎?也許你實際上在更深層次上有bug。可以肯定的是,使用這個集合,你的單元測試總是會失敗。如果你需要捕獲一個你不知道的異常,那就趕上那個特定的類型,儘管你已經拋出了一個已知的異常,但我會建議你先解決這個問題。 –

你可能感兴趣的:(java.lang.exception_如何解決java.lang.AssertionError:期望的異常:Mockito中的java.lang.Exception...)