当前位置:   article > 正文

Spring boot 整合mockito

spring boot 整合mockito

spring boot 整合mockito和spring整合mockito是一样的,没什么区别

一 引入依赖:

  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <scope>test</scope>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mockito</groupId>
  8. <artifactId>mockito-all</artifactId>
  9. <version>1.8.5</version>
  10. <scope>test</scope>
  11. </dependency>

 

实体类:

  1. public class Person {
  2. private final int id;
  3. private final String name;
  4. public Person(int id, String name) {
  5. this.id = id;
  6. this.name = name;
  7. }
  8. public int getId() {
  9. return id;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. }

dao:

  1. public interface PersonDao {
  2. Person getPerson(int id);
  3. boolean update(Person person);
  4. }

 

 service

  1. public class PersonService {
  2. private final PersonDao personDao;
  3. public PersonService(PersonDao personDao) {
  4. this.personDao = personDao;
  5. }
  6. public boolean update(int id, String name) {
  7. Person person = personDao.getPerson(id);
  8. if (person == null) {
  9. return false;
  10. }
  11. Person personUpdate = new Person(person.getId(), name);
  12. return personDao.update(personUpdate);
  13. }
  14. }

 

在test目录写测试代码:

  1. import static org.junit.Assert.assertFalse;
  2. import static org.junit.Assert.assertTrue;
  3. import static org.mockito.Matchers.eq;
  4. import static org.mockito.Matchers.isA;
  5. import static org.mockito.Mockito.mock;
  6. import static org.mockito.Mockito.never;
  7. import static org.mockito.Mockito.times;
  8. import static org.mockito.Mockito.verify;
  9. import static org.mockito.Mockito.when;
  10. import org.junit.Before;
  11. import org.junit.Test;
  12. import com.demo.mockito.bean.Person;
  13. import com.demo.mockito.dao.PersonDao;
  14. import com.demo.mockito.service.PersonService;
  15. /**
  16. * @ClassName: PersonServiceTest
  17. * @Description: TODO
  18. * @author 刘彦青
  19. * @date 2018年7月31日
  20. *
  21. */
  22. public class PersonServiceTest {
  23. private PersonDao mockDao;
  24. private PersonService personService;
  25. @Before
  26. public void setUp() throws Exception {
  27. //模拟PersonDao对象
  28. mockDao = mock(PersonDao.class);
  29. when(mockDao.getPerson(1)).thenReturn(new Person(1, "Person1"));
  30. when(mockDao.update(isA(Person.class))).thenReturn(true);
  31. personService = new PersonService(mockDao);
  32. }
  33. @Test
  34. public void testUpdate() throws Exception {
  35. boolean result = personService.update(1, "new name");
  36. assertTrue("must true", result);
  37. //验证是否执行过一次getPerson(1)
  38. verify(mockDao, times(1)).getPerson(eq(1));
  39. //验证是否执行过一次update
  40. verify(mockDao, times(1)).update(isA(Person.class));
  41. }
  42. @Test
  43. public void testUpdateNotFind() throws Exception {
  44. boolean result = personService.update(2, "new name");
  45. assertFalse("must true", result);
  46. //验证是否执行过一次getPerson(1)
  47. verify(mockDao, times(1)).getPerson(eq(1));
  48. //验证是否执行过一次update
  49. verify(mockDao, never()).update(isA(Person.class));
  50. }
  51. }

 

Mockito使用示例

模拟对象

  1. // 模拟LinkedList 的一个对象
  2. LinkedList mockedList = mock(LinkedList.class);
  3. // 此时调用get方法,会返回null,因为还没有对方法调用的返回值做模拟
  4. System.out.println(mockedList.get(0));

模拟方法调用的返回值

  1. // 模拟获取第一个元素时,返回字符串first。 给特定的方法调用返回固定值在官方说法中称为stub。
  2. when(mockedList.get(0)).thenReturn("first");
  3. // 此时打印输出first
  4. System.out.println(mockedList.get(0));

模拟方法调用抛出异常

  1. // 模拟获取第二个元素时,抛出RuntimeException
  2. when(mockedList.get(1)).thenThrow(new RuntimeException());
  3. // 此时将会抛出RuntimeException
  4. System.out.println(mockedList.get(1));

如果一个函数没有返回值类型,那么可以使用此方法模拟异常抛出

  1. doThrow(new RuntimeException("clear exception")).when(mockedList).clear();
  2. mockedList.clear();

模拟调用方法时的参数匹配

  1. // anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element
  2. when(mockedList.get(anyInt())).thenReturn("element");
  3. // 此时打印是element
  4. System.out.println(mockedList.get(999));

模拟方法调用次数

  1. // 调用add一次
  2. mockedList.add("once");
  3. // 下面两个写法验证效果一样,均验证add方法是否被调用了一次
  4. verify(mockedList).add("once");
  5. verify(mockedList, times(1)).add("once");

校验行为

  1. // mock creation
  2. List mockedList = mock(List.class);
  3. // using mock object
  4. mockedList.add("one");
  5. mockedList.clear();
  6. //verification
  7. verify(mockedList).add("one");
  8. verify(mockedList).clear();

模拟方法调用(Stubbing)

  1. //You can mock concrete classes, not just interfaces
  2. LinkedList mockedList = mock(LinkedList.class);
  3. //stubbing
  4. when(mockedList.get(0)).thenReturn("first");
  5. when(mockedList.get(1)).thenThrow(new RuntimeException());
  6. //following prints "first"
  7. System.out.println(mockedList.get(0));
  8. //following throws runtime exception
  9. System.out.println(mockedList.get(1));
  10. //following prints "null" because get(999) was not stubbed
  11. System.out.println(mockedList.get(999));
  12. verify(mockedList).get(0);

参数匹配

  1. //stubbing using built-in anyInt() argument matcher
  2. when(mockedList.get(anyInt())).thenReturn("element");
  3. //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
  4. when(mockedList.contains(argThat(isValid()))).thenReturn("element");
  5. //following prints "element"
  6. System.out.println(mockedList.get(999));
  7. //you can also verify using an argument matcher
  8. verify(mockedList).get(anyInt());
  9. //argument matchers can also be written as Java 8 Lambdas
  10. verify(mockedList).add(someString -> someString.length() > 5);

校验方法调用次数

  1. //using mock
  2. mockedList.add("once");
  3. mockedList.add("twice");
  4. mockedList.add("twice");
  5. mockedList.add("three times");
  6. mockedList.add("three times");
  7. mockedList.add("three times");
  8. //following two verifications work exactly the same - times(1) is used by default
  9. verify(mockedList).add("once");
  10. verify(mockedList, times(1)).add("once");
  11. //exact number of invocations verification
  12. verify(mockedList, times(2)).add("twice");
  13. verify(mockedList, times(3)).add("three times");
  14. //verification using never(). never() is an alias to times(0)
  15. verify(mockedList, never()).add("never happened");
  16. //verification using atLeast()/atMost()
  17. verify(mockedList, atLeastOnce()).add("three times");
  18. verify(mockedList, atLeast(2)).add("five times");
  19. verify(mockedList, atMost(5)).add("three times");

模拟无返回方法抛出异常

  1. doThrow(new RuntimeException()).when(mockedList).clear();
  2. //following throws RuntimeException:
  3. mockedList.clear();

校验方法调用顺序

  1. // A. Single mock whose methods must be invoked in a particular order
  2. List singleMock = mock(List.class);
  3. //using a single mock
  4. singleMock.add("was added first");
  5. singleMock.add("was added second");
  6. //create an inOrder verifier for a single mock
  7. InOrder inOrder = inOrder(singleMock);
  8. //following will make sure that add is first called with "was added first, then with "was added second"
  9. inOrder.verify(singleMock).add("was added first");
  10. inOrder.verify(singleMock).add("was added second");
  11. // B. Multiple mocks that must be used in a particular order
  12. List firstMock = mock(List.class);
  13. List secondMock = mock(List.class);
  14. //using mocks
  15. firstMock.add("was called first");
  16. secondMock.add("was called second");
  17. //create inOrder object passing any mocks that need to be verified in order
  18. InOrder inOrder = inOrder(firstMock, secondMock);
  19. //following will make sure that firstMock was called before secondMock
  20. inOrder.verify(firstMock).add("was called first");
  21. inOrder.verify(secondMock).add("was called second");
  22. // Oh, and A + B can be mixed together at will

校验方法是否从未调用

  1. //using mocks - only mockOne is interacted
  2. mockOne.add("one");
  3. //ordinary verification
  4. verify(mockOne).add("one");
  5. //verify that method was never called on a mock
  6. verify(mockOne, never()).add("two");
  7. //verify that other mocks were not interacted
  8. verifyZeroInteractions(mockTwo, mockThree);

快速创建Mock对象

  1. public class ArticleManagerTest {
  2. @Mock private ArticleCalculator calculator;
  3. @Mock private ArticleDatabase database;
  4. @Mock private UserProvider userProvider;
  5. @Before
  6. public void before(){
  7. MockitoAnnotations.initMocks(this);
  8. }
  9. }

自定义返回不同结果

  1. when(mock.someMethod("some arg"))
  2. .thenThrow(new RuntimeException()) // 第一次会抛出异常
  3. .thenReturn("foo"); // 第二次会返回这个结果
  4. //First call: throws runtime exception:
  5. mock.someMethod("some arg"); // 第一次
  6. //Second call: prints "foo"
  7. System.out.println(mock.someMethod("some arg")); // 第二次
  8. //Any consecutive call: prints "foo" as well (last stubbing wins).
  9. System.out.println(mock.someMethod("some arg")); // 第n次(n> 2),依旧以最后返回最后一个配置

对返回结果进行拦截

  1. when(mock.someMethod(anyString())).thenAnswer(new Answer() {
  2. Object answer(InvocationOnMock invocation) {
  3. Object[] args = invocation.getArguments();
  4. Object mock = invocation.getMock();
  5. return "called with arguments: " + args;
  6. }
  7. });
  8. //the following prints "called with arguments: foo"
  9. System.out.println(mock.someMethod("foo"));

Mock函数操作

可以通过doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() 来自定义函数操作。

暗中调用真实对象

  1. List list = new LinkedList();
  2. List spy = spy(list);
  3. //optionally, you can stub out some methods:
  4. when(spy.size()).thenReturn(100);
  5. //using the spy calls *real* methods
  6. spy.add("one");
  7. spy.add("two");
  8. //prints "one" - the first element of a list
  9. System.out.println(spy.get(0));
  10. //size() method was stubbed - 100 is printed
  11. System.out.println(spy.size());
  12. //optionally, you can verify
  13. verify(spy).add("one");
  14. verify(spy).add("two");

改变默认返回值

  1. Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
  2. Foo mockTwo = mock(Foo.class, new YourOwnAnswer());

捕获函数的参数值

  1. ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
  2. verify(mock).doSomething(argument.capture());
  3. assertEquals("John", argument.getValue().getName());

部分Mock

  1. //you can create partial mock with spy() method:
  2. List list = spy(new LinkedList());
  3. //you can enable partial mock capabilities selectively on mocks:
  4. Foo mock = mock(Foo.class);
  5. //Be sure the real implementation is 'safe'.
  6. //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
  7. when(mock.someMethod()).thenCallRealMethod();

重置Mock

  1. List mock = mock(List.class);
  2. when(mock.size()).thenReturn(10);
  3. mock.add(1);
  4. reset(mock);
  5. //at this point the mock forgot any interactions & stubbing

序列化

  1. List<Object> list = new ArrayList<Object>();
  2. List<Object> spy = mock(ArrayList.class, withSettings()
  3. .spiedInstance(list)
  4. .defaultAnswer(CALLS_REAL_METHODS)
  5. .serializable());

检查超时

  1. //passes when someMethod() is called within given time span
  2. verify(mock, timeout(100)).someMethod();
  3. //above is an alias to:
  4. verify(mock, timeout(100).times(1)).someMethod();
  5. //passes when som`eMethod() is called *exactly* 2 times within given time span
  6. verify(mock, timeout(100).times(2)).someMethod();
  7. //passes when someMethod() is called *at least* 2 times within given time span
  8. verify(mock, timeout(100).atLeast(2)).someMethod();
  9. //verifies someMethod() within given time span using given verification mode
  10. //useful only if you have your own custom verification modes.
  11. verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();

Mock详情

  1. Mockito.mockingDetails(someObject).isMock();
  2. Mockito.mockingDetails(someObject).isSpy();



作者:流水不腐小夏
链接:https://www.jianshu.com/p/77db26b4fb54
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

mockito使用指南:https://blog.csdn.net/shensky711/article/details/52771493

https://www.jianshu.com/p/77db26b4fb54

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/366785
推荐阅读
相关标签
  

闽ICP备14008679号