0

I have a class which I have annotated as @injectMock. This class has a constructor which loads messages from in put stream as below:

public class RegistrationEventValidator {
    private Properties validationMessages;

    RegistrationEventValidator() {
        validationMessages = new Properties();
        try {
            validationMessages.load(RegistrationEventValidator.class.getClassLoader().getResourceAsStream("ValidationMessages.properties"));
        } catch (IOException e) {
            throw new InternalErrorException("Failed loading ValidationMessages.properties");
        }
    }
}

My test covers up until the "catch exception". How do I unit test that part? Thank you.

This is what I have so far and I am getting this error: "org.opentest4j.AssertionFailedError: Expected com.autonation.ca.exception.InternalErrorException to be thrown, but nothing was thrown"

@Test
void test_validation_messages_properties() throws IOException {
    //given
    List<String> errors = new ArrayList<>();
    Event<AuthEventDetails> event = new Event<>();
    AuthEventDetails request = new AuthEventDetails();
    event.setCustomerId(RandomStringUtils.random(65));
    request.setFirstName(RandomStringUtils.random(256));
    request.setLastName(RandomStringUtils.random(256));
  
    event.setEventDetails(request);

    doThrow(new InternalErrorException("Failed loading ValidationMessages.properties")).when(validationMessages).load(any(InputStream.class));

    assertThrows(InternalErrorException.class, () -> registrationEventValidator.validate(event, errors));
}
idanz
  • 821
  • 1
  • 6
  • 17
  • 1
    You annotated object under test with `@InjectMocks`, but `RegistrationEventValidator` constructor takes no arguments - what are you expecting to inject? – Lesiak Nov 14 '22 at 20:14
  • @Lesiak RegistrationEventValidator class. – clement mensah Nov 15 '22 at 15:33
  • Does this answer your question? [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/questions/74027324/why-is-my-class-not-calling-my-mocked-methods-in-unit-test) – knittl Nov 15 '22 at 23:28
  • You struggle with this test because you violate an impotant rule of Java programming: Constructors should not do any work other than assigning its parameters to (`final`) object member variables and (very) simple sanity checks. Especially they should not call other methods. The second rule you violate is, that a class should not instantiate its dependencies itself but get them injected as constructor parameters. – Timothy Truckle Nov 22 '22 at 21:45

0 Answers0