Spring unit test issue with Validator

前端 未结 2 1962
無奈伤痛
無奈伤痛 2021-01-22 11:19

I am trying to write unit test for a validator class that I have. So within my UniqueEmailValidator class, I injected a @Service component to check if it exist.

         


        
相关标签:
2条回答
  • 2021-01-22 12:09

    The actual problem is deep down in the stack-trace that you've provided:

    Caused by: java.lang.NoSuchMethodException: com.x.x.validator.UniqueEmailValidator.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    ... 52 more
    

    This error message is thrown because there is some code that is trying to instantiate the UniqueEmailValidator class constructor without any parameters. The problem will be resolved by adding a default constructor to this class:

    public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
        public UniqueEmailValidator() {
        }
        ...
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-22 12:11

    You need to have a default non argument public constructor. If you need to pass a Spring component into your validator, you may face a problem in test.

    I solved it by having a component which holds a service and has a static method to give the service.

    0 讨论(0)
提交回复
热议问题