1. 程式人生 > >Mockito單元測試-註解的詳細使用

Mockito單元測試-註解的詳細使用



1,@Mock

  1. @Target(FIELD)
  2. @Retention(RUNTIME)
  3. @Documented
  4. public@interfaceMock{
  5. Answers answer()defaultAnswers.RETURNS_DEFAULTS;
  6. String name()default"";
  7. Class<?>[] extraInterfaces()default{};
  8. }

@Mock註解,我們用來初始化Mock物件。代替我們在不使用註解的場景中使用的Mockito.mock(xxx.class)方法。

2,@Spy

  1. @Retention(RUNTIME)
  2. @Target(FIELD
    )
  3. @Documented
  4. public@interfaceSpy{}

@Spy註解,具體的使用我們可以參考文件

  1. *<h4>Important gotcha on spying real objects!</h4>
  2. *<ol>
  3. *<li>Sometimes it's impossible or impractical to use {@linkMockito#when(Object)}for stubbing spies.
  4. *Thereforefor spies it is recommended to always use <code>
    doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
  5. * family of methods for stubbing.Example:
  6. *
  7. *<pre class="code"><code class="java">
  8. *List list =newLinkedList();
  9. *List spy = spy(list);
  10. *
  11. *//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
  12. *   when(spy.get(0)).thenReturn("foo");
  13. *
  14. *//You have to use doReturn() for stubbing
  15. *   doReturn("foo").when(spy).get(0);
  16. *</code></pre>
  17. *</li>
  18. *
  19. *<li>Mockito<b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
  20. *Soif you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
  21. * and their effect on real instance state.
  22. *The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
  23. * you won't see any effects on the real instance.</li>
  24. *
  25. *<li>Watch out forfinal methods.
  26. *Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
  27. *Also you won't be able to verify those method as well.
  28. *</li>
  29. *</ol>
  30. *
  31. *<p>
  32. *<strong>One last warning :</strong>if you call <code>MockitoAnnotations.initMocks(this)</code> in a
  33. *superclass<strong>constructor</strong> then this will not work.It is because fields
  34. * in subclass are only instantiated after superclass constructor has returned.
  35. *It's better to use @Before.
  36. *<strong>Instead</strong> you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in
  37. *{@link org.mockito.runners.MockitoJUnitRunner}.

3,@InjectMocks

Mockito通過此註解會自動注入mocks 物件到我們註解的變數中。如果注入失敗,不會通知我們,所以我們需要自己對失敗的物件做處理。

4,MockitoAnnotations.initMocks

初始化我們的Mock註解。

5,例項

  1. package com.raycloud.dmj.services.gray;
  2. import com.raycloud.cache.CacheException;
  3. import com.raycloud.cache.ICache;
  4. import com.raycloud.dmj.domain.Configurable;
  5. import com.raycloud.grayrelease.HitReceipt;
  6. import junit.framework.TestCase;
  7. import org.junit.Before;
  8. import org.junit.Test;
  9. import org.mockito.*;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. /**
  15. * GrayServiceTest
  16. * Created by jinglongjun on 16/3/4.
  17. */
  18. publicclassGrayServiceTestextendsTestCase{
  19. @Spy
  20. @InjectMocks
  21. privateGrayService grayService;
  22. @Mock
  23. Configurable config;
  24. @Mock
  25. ICache cache;
  26. @Before
  27. publicvoid setUp(){
  28. MockitoAnnotations.initMocks(this);
  29. }
  30. @Test
  31. publicvoid testList(){
  32. List<String> strs =newArrayList<String>();
  33.        strs.add("1");
  34.        strs.add("2");
  35. System.out.println(strs);
  36. }
  37. /**
  38.     * 正常碰撞進入快取
  39.     *
  40.     * @throws CacheException
  41.     */
  42. @Test
  43. publicvoid testSetCacheList()throwsCacheException{
  44. HitReceipt hitReceipt =newHitReceipt();
  45.        hitReceipt.setUid("1");
  46.        hitReceipt.setNick("1");
  47.        hitReceipt.setForward(true);
  48. Map<String,HitReceipt> users =newHashMap<String,HitReceipt>();
  49. Mockito.when(cache.get(GrayUtil.getCacheUsers())).thenReturn(users);
  50.        grayService.setCacheList(hitReceipt);
  51.        grayService.setCacheList(hitReceipt);
  52.        grayService.setCacheList(hitReceipt);
  53.        grayService.setCacheList(hitReceipt);
  54. Mockito.verify(cache,Mockito.atLeastOnce()).set(GrayUtil.getCacheUsers(), users);
  55. }