MyClass有两个依赖项(场地和录制),所以你必须模仿它们。
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,等等。因此,最好存根中使用的所有方法
类名
.