Mockito etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Mockito etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

10 Ekim 2022 Pazartesi

Mockito @Captor Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.mockito.Captor;
Açıklaması şöyle
It allows the creation of a field-level argument captor. It is used with the Mockito’s verify() method to get the values passed when a method is called

22 Aralık 2021 Çarşamba

Mockito @MockitoSettings Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
Örneği ilk burada gördüm. Aslında bu çözümler sadece UnnecessaryStubbingException fırlatılmasını engelliyor. Testleri halen temizlemekte fayda var. Verilen hata şöyle
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at pl.nsn.railway.grkeepalive.MyTest.testLenient(MyTest.java:41)
  2. -> at pl.nsn.railway.grkeepalive.MyTest.testLenient(MyTest.java:42)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.

Örnek - JUnit 4
Şöyle yaparız. Böylece artık UnnecessaryStubbingException dikkate alınmaz
@RunWith(MockitoJUnitRunner.Silent.class)
public class FooTest {
  ...
}
Örnek - JUnit 5 
@MockitoSettings(strictness = Strictness.LENIENT) kullanırız. Böylece artık UnnecessaryStubbingException dikkate alınmaz
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class MyTest {

  public class MyFrameworkRuntimeProvider {
    String getContainer(String name) {
      return name;
    }
    String getComponentHandle() {
     return null;
    }
  }
  //@Mock
  //MyFrameworkRuntimeProvider mock;

  @Test
  public void testLenient(){

    MyFrameworkRuntimeProvider mock = Mockito.mock(MyFrameworkRuntimeProvider.class);
    Mockito.when(mock.getContainer("1")).thenReturn("1");
    Mockito.when(mock.getContainer("2")).thenReturn("2"); //not called
    Mockito.when(mock.getComponentHandle()).thenReturn(null);//not called
    
    mock.getContainer("1");

    Mockito.verify(mock,Mockito.atLeast(1)).getContainer(Mockito.anyString());
  }
}

14 Haziran 2021 Pazartesi

Mockito willThrow + given Kullanımı

Giriş
Mockito, Behavior Driven Development (BDD) yöntemiyle test edebilme imkanı da sunar. Bunun için org.mockito.BDDMockito kullanılır

Örnek
Şöyle yaparız
@Test
public void myTest() throws Exception {
  MyService service = spy(MyService.class);

  willThrow(new MyServiceException("abc msg",511))
    .given(service)
    .hi()
  ;

  // As pointed out by @eis, you can still use willAnswer
  // willAnswer(
  //   invocation -> { throw new MyServiceException("abc msg",511);}
  // )
  //   .given(service)
  //   .hi()
  // ;

  
  MyJsonResponse actual = service.hello();

  Assert.assertNotNull(actual);
  assertEquals(511, actual.getHttpResponse());
}

14 Aralık 2020 Pazartesi

Mockito Kullanımı

Giriş
Mockito kullanabilmek için API'yi bilmek gerekiyor. API'nin çoğu Mockito sınıfı etrafında tanımlı.

Maven
"mockito-all" eski bir dependency ve artık kullanılmamalı

Örnek - Anotasyon Olmadan
Şu satırı dahil ederiz. 
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>3.8.0</version>
  <scope>test</scope>
</dependency>
Örnek - Anotasyon İle JUnit 5
JUnit 5 ile kullanmak için şöyle yaparız. 
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.7.1</version>
  <scope>test</scope>
</dependency>

<dependency>
 <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.7.1</version>
  <scope>test</scope>
</dependency>

<dependency>
 <groupId>org.junit.platform</groupId>
  <artifactId>junit-platform-launcher</artifactId>
  <version>1.7.1</version>
  <scope>test</scope>
</dependency>

Mock object yaratma ve davranışı tanımlama işlemleri burada yapılır

Mockito'ya ait runner tarafından koşturulan testlerde kullanılır

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);
}


19 Kasım 2019 Salı

Mockito InOrder Arayüzü

constructor
Şöyle yaparız
Foo mockFoo = Mockito.mock(Foo.class);
InOrder orderVerifier = Mockito.inOrder(mockFoo);
verify metodu
Örnek
Şöyle yaparız.
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();
Örnek
Şöyle yaparız.
InOrder inOrder = Mockito.inOrder(mock);
inOrder.verify(mock).addPost(any(Post.class));
inOrder.verify(mock).getAllPosts();