通常,不要嘲笑被测类。如果您的测试是针对Person的,则您永远都不会看到
Mockito.mock(Person.class)它,因为这很明显地表明您正在测试模拟框架而不是被测系统。
相反,您可能想创建一个
spy(newPerson()),它将使用一个真正的构造函数创建一个真实的Person实现,然后将其数据复制到Mockito生成的代理中。您可以
MockingDetails.getInvocations()用来反省检查是否已调用每个getter。
// This pre is untested, but should get the point across. Edits welcome.// 2016-01-20: Integrated feedback from Georgios Stathis. Thanks Georgios!@Testpublic void callAllGetters() throws Exception { Person personSpy = spy(new Person()); personSpy.getFirstname(); personSpy.getLastname(); assertAllGettersCalled(personSpy, Person.class);}private static void assertAllGettersCalled(Object spy, Class<?> clazz) { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); Set<Method> setOfDescriptors = beanInfo.getPropertyDescriptors() .stream() .map(PropertyDescriptor::getReadMethod) .filter(p -> !p.getName().contains("getClass")) .collect(Collectors.toSet()); MockingDetails details = Mockito.mockingDetails(spy); Set<Method> setOfTestedMethods = details.getInvocations() .stream() .map(InvocationOnMock::getMethod) .collect(Collectors.toSet()); setOfDescriptors.removeAll(setOfTestedMethods); // The only remaining descriptors are untested. assertThat(setOfDescriptors).isEmpty();}
有可能是一个方法来调用
verify和
invoke对的Mockito产生的间谍,但似乎很脆弱,非常依赖于内部的Mockito。
顺便说一句,测试bean风格的吸气剂似乎在浪费时间/精力。通常,重点关注可能会更改或中断的测试实现。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)