我的应用程序使用 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() 方法编写单元测试,它应该
您有两个 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
}
请注意,如果您没有指定任何模拟依赖项的返回值(with when()
),它将返回返回类型的默认值 - 对象为 null,原始数字为 0,布尔值为 false 等。所以它将是最好存根中使用的所有方法MyClass
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句