使用 Mockito 对基于 Guice 的单元测试 class

Using Mockito to unit test Guice based class

我的应用程序使用 Google Guice 依赖注入框架。我现在找不到为我的 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());
}

我想为子class中的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 的实例并断言预期结果:

例如:"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
}

请注意,如果您未指定任何模拟依赖项(使用 when())的 return 值,它将 return 默认值 return 类型 - 对象为 null,原始数字为 0,布尔值为 false,等等。因此最好将 MyClass.

中使用的所有方法存根