![](/img/trans.png)
[英]Mocking the call to another method of another class inside the method being tested
[英]Mocking a class inside the tested method
我必须模拟的课程有问题。
经过测试的方法如下所示:
testedMethod(Date from, Date to, Set set1, Set set2, SomeContext context) { method body };
现在在方法主体内部,使用了一个类。 用法如下所示:
List list = ComponentsFetcher.getComponent(String string1, context, from, to, String string2);
整个测试方法(略有简化)如下所示:
public static final long testedMethod(Date from, Date to, Set set1, Set set2, SomeContext context) {
long returnedLong = 0;
List list1 = ComponentsFetcher.getComponent(String string1, context, from, to, String string2);
List list2 = ComponentsFetcher.getComponent(String string3, context, from, to, String string4);
returnedLong = TestedMethodsClass.anotherMethod(from, to, set1, set2, list1, list2
return returnedLong;
};
这个ComponentsFetcher.getComponent()
方法正在做很多事情,但是我要做的只是获取此list
,我知道此列表的样子,我可以简单地创建它并稍后在经过测试的方法中使用它。
所以我想像这样模拟ComponentsFetcher.getComponent()
:
private void mockComponentsFetcher(Date from, Date to, ComponentsContext context, List list1, List list2) throws SomeBusinessException {
Mockito.mock(ComponentsFetcher.class);
Mockito.when(ComponentsFetcher.getComponent(string1, context, from, to, string2)).thenReturn(list1);
Mockito.when(ComponentsFetcher.getComponent(string3, context, from, to, string4)).thenReturn(list2);
}
最后,@ @Test
方法:
@Test
public void testTestedMethod() throws ParseException, SomeBusinessException {
//given
Date from = DateHelper.getDate(2011, 07, 03);
Date to = DateHelper.getDate(2012, 07, 03);
Set set1 = null; // can be null
Set set2 = DateHelper.getDate(2011, 07, 03);
Date day = DateHelper.getDate(2011, 07, 03);
List list1 = getList(new Date[]{
// contents of the list
});
List list2 = getList(new Date[]{
// contents of the list
});
//mock
ComponentsContext context = mockContext(day);
//此上下文确实无关紧要,只是为了使方法运行而对其进行了模拟。
//这是主要问题,我不知道如何在使用testedMethod的同时使用此模拟的ComponentsFetcher
mockComponentsFetcher(from, to, context, list1, list2);
//when
long months = TestedMethodsClass.testedMethod(from, to, set1, set2, context);
//then
long awaited = 12;
assertThat(months).isEqualTo(awaited);
}
但这根本没有用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.