2017-02-08 4 views
1

私はJersey & Spring-Bootで書かれたRESTサービスを持っています。 POST paramsのカスタムバリデータクラスを作成しました。私は同じことをユニットテストしたい私はそれをする方法を理解できませんでした。私のValidatorは以下のようになります。ジャージカスタムバリデーターunittest

@Retention(RetentionPolicy.RUNTIME) 
@Constraint(validatedBy = ValidTaskForCreate.Validator.class) 
public @interface ValidTaskForCreate { 
    String message() default "Invalid Request to create a Task"; 
    Class<?>[] groups() default {}; 

Class<? extends Payload>[] payload() default {}; 
public class Validator implements ConstraintValidator<ValidTaskForCreate, Task> { 

    @Override 
    public void initialize(ValidTaskForCreate constraintAnnotation) { 
    } 

    @Override 
    public boolean isValid(final Task task, ConstraintValidatorContext context) { 
      context.disableDefaultConstraintViolation(); 
      if(task.getName() == null || task.getName().isEmpty()) { 
       context.buildConstraintViolationWithTemplate("Task name should be specified").addConstraintViolation(); 
       return false; 
      } 

      if(task.getTaskType() == null) {  
       context.buildConstraintViolationWithTemplate("Specify a valid TaskType in the range of [1..3]").addConstraintViolation(); 
       return false; 
      } 
      return true; 
     } 

    } 
} 

は、今私は、さまざまなタスクのオブジェクトを渡すことではisValid()関数をテストしたいです。私は今このメソッドをどのように呼び出すべきかわかりません。 は私がのisValid()を呼び出すには、次のように

ValidTaskForCreate.Validator taskValidator = null; 
    taskValidator = new ValidTaskForCreate.Validator(); 

をValidatorクラスのインスタンスを作成することができ、i)は(taskValidator.isValidを使用することができます。しかし、私は2番目のパラメータとして渡すConstraintValidatorContextオブジェクトを作成する方法を知らない。

UnitTestのカスタム検証クラスには、このような方法がありますか?

答えて

1

しかし、第2パラメータとして渡すConstraintValidatorContextオブジェクトの作成方法はわかりません。

Mockitoを使用してください。次に、正しいメソッドが呼び出されたことを確認します。これは、依存関係が関与している場合のユニットの動作をテストする方法です。

private ConstraintValidatorContext context; 
private ConstraintValidatorContext.ConstraintViolationBuilder builder; 

@Before 
public void setup() { 
    // mock the context 
    context = Mockito.mock(ConstraintValidatorContext.class); 

    // context.buildConstraintViolationWithTemplate returns 
    // ConstraintValidatorContext.ConstraintViolationBuilder 
    // so we mock that too as you will be calling one of it's methods 
    builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class); 

    // when the context.buildConstraintViolationWithTemplate is called, 
    // the mock should return the builder. 
    Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString())) 
     .thenReturn(builder); 
} 

@Test 
public void test() { 
    // call the unit to be tested 
    boolean result = ..isValid(badTask, context); 

    // assert the result 
    assertThat(result).isFalse(); 

    // verify that the context is called with the correct argument 
    Mockito.verify(context) 
      .buildConstraintViolationWithTemplate("Task name should be specified"); 
} 

Mockitoの使用に注意してください。ほとんどの場合、静的インポートを使用して、あまり冗長にならないようにするだけです。私はちょうどそれをより読みやすくしたいと思った。