Search code examples
javaunit-testingdependency-injectionmockitoguice

Using Mockito to unit test Guice based class


My application uses Google Guice dependency injection framework. Im now having trouble figuring out a way to write unit tests for my class.

private final Person aRecord;

@Inject
public MyClass(Venue venue, @Assisted("record") Record myRecord) {
    super(venue,myRecord);
    aRecord = (Person) myRecord;
}

public void build() throws Exception {
    super.build();
    super.getParentRecord().setJobType(aRecord.getJobType());
    super.getParentRecord().setHairColor(aRecord.getHairColor());
    super.getParentRecord().setEyeColor(aRecord.getEyeColor());
}

I want to write a unit test for the build() method in the child class, it should

  • Ensure that when super.build() gets called all of the basic information on the super.getParentRecord() is populated e.g. age, gender etc.
  • Ensure an exception is thrown in the build() method if aRecord.getJobType() is null
  • Ensure an exception is thrown in the build() method if aRecord.getHairColor() is null
  • Ensure an exception is thrown in the build() method if aRecord.getEyeColor() is null

Solution

  • You have two dependencies of MyClass (Venue and Record) so you have to mock those.

    import static org.mockito.Mockito.mock;
    import static org.mockito.Mockito.when;
    ...
    Venue venueMock = mock(Venue.class);
    Record recordMock = mock(Record.class);
    

    Then in your unit test you have to create an instance of MyClass and assert the expected result:

    For example: "Ensure an exception is thrown in the build() method if aRecord.getJobType() is null"

    @Test(expected=RuntimeException.class)// or whatever exception you expect
    public void testIfExceptionIsThrownWhengetJobTypeReturnsNull() throws Throwable {
        Venue venueMock = mock(Venue.class);   //create the mocks
        Record recordMock = mock(Record.class);//create the mocks
        when(recordMock.getJobType()).thenReturn(null); //specify the behavior of the components that are not relevant to the tests
    
        MyClass myClass = new MyClass(venueMock, recordMock); 
        myClass.build();
        //you can make some assertions here if you expect some result instead of exception
    }
    

    Note that if you don't specify the return value of any of the mocked dependencies (with when()) it will return the default value for the return type - null for objects, 0 for primitive numbers, false for boolean, etc. So it will be best to stub all of the methods that are used in MyClass.