spring mock
引入jar
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
使用方式1:
@InjectMocks
@Autowired
private OrderProduceWorker OrderProduceWorker;
//被mock类必须是 OrderProduceWorker 属性,否则不起作用
@Mock
private OrderProduce OrderProduce;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testDoProcess() throws Exception {
Mockito.when(orderProduce.orderProduce(Mockito.anyLong())).thenReturn(SUCCESS);
.....................................................
.....................................................
}
另类玩法:
@Autowired
private OrderProduceWorker OrderProduceWorker;
//被mock类必须 **不是** OrderProduceWorker 属性,要想启作用 见 @Before
@Mock
private OrderProduce OrderProduce;
@Before
public void setup() {
//init
MockitoAnnotations.initMocks(this);
//手工注入替换
OrderProduceWorker worker = AopTestUtils.getTargetObject(this.orderProduceWorker);
// You could have the same result by orderProduceWorker add @InjectMocks annotation
ReflectionTestUtils.setField(worker, "orderProduce", this.orderProduce);
}
@Test
public void testDoProcess() throws Exception {
Mockito.when(orderProduce.orderProduce(Mockito.anyLong())).thenReturn(SUCCESS);
.....................................................
.....................................................
}
Mockito.when的一个问题是你传递给它的参数是你试图存根的表达式.因此,当您使用Mockito.when两次进行相同的方法调用时,第二次使用它时,您实际上将获得第一次存根的行为.
我实际上建议不要使用Mockito.when.使用它时可能会遇到许多陷阱 – 很多情况下,当您需要其他语法时. “更安全”的替代语法是Mockito方法的“do”系列.
doReturn(value).when(mock).method(arguments ...);
doThrow(exception).when(mock).method(arguments ...);
doAnswer(answer).when(mock).method(arguments ...);
所以在你的情况下,你想要
doThrow(new BadSqlGrammarException(??, ??, ??)).when(accountMapper).createBadGrammarException();
如果你开始使用Mockito,那么我建议你学会使用“do”系列.它们是模拟void方法的唯一方法,而Mockito文档特别提到了这一点.但是只要Mockito.when可以使用它们就可以使用它们.因此,如果您使用“do”系列,您的测试结果会更加一致,而学习曲线也会减少.
摘自:http://www.voidcn.com/article/p-sqbaaxbk-bth.html
spring boot mock 参见:https://www.jianshu.com/p/ecbd7b5a2021