Mockito学习(二)

这里总结几个我做个test的用法。

 

 1. argument matcher, such as anyInt(); when .. thenreturn..; verify never(), atleast(), atmost()

 

		List mock = mock(List.class);
		/*
		 * stub the mock. with return value, will be" when ...", then
		 * " thenReturn...". without return value, will be " do
		 */
		//
		when(mock.get(anyInt())).thenReturn("123");
              // simulate void function,
		doThrow(new RuntimeException("test the error")).when(mock).clear();
		mock.get(123);
		verify(mock).get(anyInt());

		mock.add("1");

		mock.add("2");
		mock.add("2");

		verify(mock).add("1");

		verify(mock, times(2)).add("2");

		// will fail, because three times will be invoked
		// verify(mock).add(anyString());

		verify(mock, never()).add("3");

		verify(mock, atLeastOnce()).add("1");

		verify(mock, atMost(5)).add("2");

		mock.clear();

 2.Inorder,验证顺序和执行次数

 List target = mock(List.class);

		target.add("1");
		target.add("2");

		InOrder inOrder = inOrder(target);
		inOrder.verify(target).add("1");
		inOrder.verify(target).add("2");

		List seq1 = mock(List.class);
		List seq2 = mock(List.class);
		List seq3 = mock(List.class);
		seq1.add("123");
		seq2.add("123");
		InOrder inOrder2 = inOrder(seq1, seq2);
		// inOrder2.verify(seq1).add("123");
		// inOrder2.verify(seq2).add("123");
		inOrder2.verify(seq1).add("123");
		inOrder2.verify(seq2).add("123");

		verify(seq1).add("123");
		verifyZeroInteractions(seq3);
		verifyNoMoreInteractions(seq1);

 3.Answer

 

		TestInterface testTarget = mock(TestInterface.class,
				new Answer<TestInterface>() {
					@Override
					public TestInterface answer(InvocationOnMock invocation)
							throws Throwable {
						Object[] arguments = invocation.getArguments();
                                               // based on arguments, you can return different value
						System.out.println(arguments.length);
						return null;
					}
				});

		testTarget.print4();
		testTarget.print4("2");
		testTarget.print4("3", "4");
		testTarget.print4("4");

   这里利用Answer可以根据传入的参数,返回不同的值,从而以可以利用一个mock对象对一个方法mock多个不同的返回值。

4.spy

 

               TestInterface inte = new ConcreteTestInterface2();
		TestInterface spy = spy(inte);

		when(spy.print2()).thenReturn(333);
                // if you want to call orignal implementation, you can call
                //  doCallRealMethod
		doCallRealMethod().when(spy).print2();

		System.out.println(spy.print1("123"));
		System.out.println(spy.print2());
		System.out.println(spy.print3());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值