使用Mockito创建模拟对象(在“Java语句”上下文中):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
在“Java类型成员”中:
${:import(org.mockito.Mock)}@Mock
${Type} ${mockName};
模拟一个void方法抛出异常:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
模拟一个void方法来执行某些操作:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object arg1 = invocation.getArguments()[0];
return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});
验证模拟方法只被调用一次:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
验证模拟方法从未被调用:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
使用Google Guava创建新的链表(对于哈希集和哈希映射也类似):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList()
我使用一个生成测试类的大型模板。以下是一个缩短版本,每个人都可以根据自己的需求进行定制:
package ${enclosing_package};
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;
@RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {
@InjectMocks
protected ${testedType} ${testedInstance};
${cursor}
@Mock
protected Logger logger;
@Before
public void setup() throws Exception {
}
@Test
public void shouldXXX() throws Exception {
fail("Not implemented.");
}
}
System.out.println(${word_selection}${});${cursor}
的意思是什么?听起来好像有一种方法可以选择一个单词并自动将其包裹在sysout
调用中,我是对的吗?如何实现? - CodyBugstein