使用Mockito对基于Guice的班级

时间:2017-12-05 10:41:35

标签: java unit-testing dependency-injection mockito guice

我的应用程序使用Google Guice依赖注入框架。我现在无法找到为我班级编写单元测试的方法。

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());
}

我想为子类中的build()方法编写一个单元测试,它应该

  • 确保在调用super.build()时,填充super.getParentRecord()的所有基本信息,例如年龄,性别等。
  • 如果aRecord.getJobType()为null,请确保在build()方法中抛出异常
  • 如果aRecord.getHairColor()为null,请确保在build()方法中抛出异常
  • 如果aRecord.getEyeColor()为null,则确保在build()方法中抛出异常

1 个答案:

答案 0 :(得分:1)

你有两个MyClass(Venue和Record)依赖项,所以你必须嘲笑它​​们。

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

然后在您的单元测试中,您必须创建MyClass的实例并断言预期结果:

例如:"如果aRecord.getJobType()为null,请确保在build()方法中抛出异常"

@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
}

请注意,如果您没有指定任何模拟依赖项的返回值(使用when()),它将返回返回类型的默认值 - 对象为null,原始数字为0,布尔值等为false。因此,最好将MyClass中使用的所有方法都存根。