[英]Using Mockito to unit test Guice based class
My application uses Google Guice dependency injection framework. 我的应用程序使用Google Guice依赖项注入框架。 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 我想在子类中为build()方法编写一个单元测试,它应该
You have two dependencies of MyClass (Venue and Record) so you have to mock those. 您有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);
Then in your unit test you have to create an instance of MyClass
and assert the expected result: 然后,在单元测试中,您必须创建
MyClass
的实例并声明预期结果:
For example: "Ensure an exception is thrown in the build() method if aRecord.getJobType() is null" 例如:“如果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
}
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
. 请注意,如果您不指定任何模拟依赖项的返回值(使用
when()
),它将为返回类型返回默认值-对象为null,原始数字为0,布尔值为false,等等。最好将MyClass
中使用的所有方法都存根。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.