简体   繁体   中英

Test ConstraintValidator with @Service

I have this ConstraintValidator which I am trying to test...

public class UniqueFurlValidator implements ConstraintValidator<Unique, String> {
    @Autowired
    private SponsorService sponsorService;

    public UniqueFurlValidator() {}

    @Override
    public void initialize(Unique unique) {
        unique.message();
    }

    @Override
    public boolean isValid(String furl, ConstraintValidatorContext context) {
        if (sponsorService != null && sponsorService.existsByFurl(furl)) {
            return false;
        }
        return true;
    }
}

The test I have written so far is...

@RunWith(SpringRunner.class)
@DataJpaTest
public class UniqueFurlValidatorTest {
    @Mock
    private EntityManager entityManager;

    @Autowired
    private SponsorService sponsorService;

    @InjectMocks
    private UniqueFurlValidator validator;

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void alreadyExistsFurlReturnsError() {

    }
}

The @Service links to the JPA repository. Please advice on how I can actually test this.

You have a very simple single class to unit test (this is a good thing). For some reason you are dragging in both SpringRunner and Mockito to help you. Spring is unnecessary here as this is not a @DataJpaTest , it is a vanilla Java class.

@RunWith(MockitoJUnitRunner.class)
public class UniqueFurlValidatorTest {
    @Mock
    private SponsorService sponsorService;

    @InjectMocks
    private UniqueFurlValidator validator;

    @Test
    public void alreadyExistsFurlIsInvalid() {
      // Given:
      given(sponsorService.existsByFurl("EXISTS")).returns(true);
      // Then:
      assertThat(validator.isValid("EXISTS", null), is(false) );
    }

    @Test
    public void newFurlIsValid() {
      assertThat(validator.isValid("NEW", null), is(true) );
    }

}

I didn't add a test for a null sponsorService as that shouldn't really be runtime logic. It is unlikely to occur (Spring would exit during Context initialisation) and it would be better asserted in a constructor anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM