6 Ocak 2020 Pazartesi

Mockito @Spy Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.mockito.Spy;
Açıklaması şöyle. Gerçek nesnenin sadece belirtilen metodları mock kodu tarafından override edilir.
To create a spy, you need to call Mockito’s static method spy() and pass it an instance to spy on. Calling methods of the returned object will call real methods unless those methods are stubbed. These calls are recorded and the facts of these calls can be verified (see further description of verify())
Eğer spy kullanmak istemiyorsak doCallRealMethod + when Kullanımı yazısına bakabilirsiniz.

Diğer Seçenekler
Bu anotasyon yerine  Mockito.spy() kullanılabilir. Şöyle yapabiliriz.
private UsersLoader loader;

@Before
public void setUp() {
  loader = Mockito.spy(new UsersLoader());
}
Mock'lanacak Metod
Spy nesne yaratıldıktan sonra bir veya daha fazla metodunu mock'lamak gerekir. Bu adım için mutlaka
Mockito.doReturn + .when
şeklinde kullanmak gerekir. Eğer 
Mockito.when + thenReturn
şeklinde kullanırsak gerçek metodun çağrıldığını görürüz. Yani istenilen şekilde çalışmıyor

Örnek
Şöyle yaparız
@Test
void testSetConnectionPool() {
  DataSourceSetter dataSourceSetter = Mockito.spy(new DataSourceSetter());

  //Mock the creation of HikariDataSource because HikariDataSource tries to connect to DB
  HikariDataSource mockHikariDataSource = Mockito.mock(HikariDataSource.class);
  Mockito.doReturn(mockHikariDataSource).when(dataSourceSetter).getHikariDataSource();
  ...
}
Mocklanacak Sınıf Final Olmamalı
Yoksa şöyle bir hata alırız.
Mockito cannot mock/spy because :
 - final class
Örnek
Şöyle yaparız
@Spy // Annotation added here
DownloadStatusListenerImpl status;

@Before
public void before() {
  MockitoAnnotations.initMocks(this);
}
veya anotasyon kullanmak istemiyorsak şöyle yaparız.
@Before
public void before() {
  status = Mockito.spy(new DownloadStatusListenerImpl());
}
Örnek - Tek metod mock'lamak
Elimizde şöyle bir kod olsun. Sadece getMyObject metodunu override etmek isteyelim.
Class A
{
   MyObject o;
   A() {
     //some other code
     o = new MyObject();
     //some other code
   }

  MyObject getMyObject(){return o;}
}
Şöyle yaparız. Burada doReturn + when kullanımına dikkat!
@Test
public void test1(){
  MyObject mocked = Mockito.mock(MyObject.class);
  A spyA = Mockito.spy(new A());
  doReturn(mocked).when(spyA).getMyObject();
  ...
}
Örnek
Şöyle yaparız
@Spy
private TestClass testClass;

@Test
public void calculateTest() {
  int expected = 100;
  Mockito.when(testClass.getShape(1)).thenReturn("square");
  int actual = testClass.calculate();
  assertEquals(expected, actual);
}


Hiç yorum yok:

Yorum Gönder