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

14 Ocak 2020 Salı

PowerMockito Whitebox Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.powermock.reflect.Whitebox;
getInternalState metodu
Sınıfın private alanının değeri alınabilir.

invokeConstructor metodu
Private builder içeren sınıf yaratılabilir.

invokeMethod metodu
Private metod çağrılabilir.

setInternalState metodu
Public olmayan alana değer atanabilir.
Örnek - static alan
Elimizde şöyle bir kod olsun
public class Foo {
  private static Bar b;
}
Bu alan static olduğu için şöyle yaparız. Buradar mockBar Bar tipinden olduğu için ve Bar tipinden tek alan olduğu için sıkıntık çıkmıyor.
Whitebox.setInternalState(Foo.class, mockBar);
Eğer Bar tipinden iki tane alan olsaydı alan ismini kullanmak gerekirdir. Bu durumda şöyle yaparız
Whitebox.setInternalState(Foo.class,"bar", mockBar);

30 Aralık 2019 Pazartesi

PowerMockito whenNew + withAnyArguments + thenReturn Kullanımı - Unit Under Test İçinde Yaratılan Nesneyi Mocklar

Giriş
Kendi sınıfım içinde dışarıdan verilmeyen ancak new'lenen nesneyi mocklamak için kullanılır. Unit Under Test yani kendi sınıfımı @PrepareForTest anotasyonu ile PowerMock'a test başında göstermek gerekir.

Örnek
Şöyle yaparız. Burada Unit Under Test içinde new'lenen mock nesneyi Mockito ile yaratıyoruz.
ConcreteClass concreteObject = mock(ConcreteClass.class);
PowerMockito.whenNew(ConcreteClass.class)
  .withAnyArguments().thenReturn(concreteObject);
Örnek
Elimizde şöyle bir kod olsun. 
class ToBeTest{
  public ToBeTest(){}
    public boolean doWork(){
        OtherObject obj=new OtherObject();
        return obj.work();
    }
}
Şöyle yaparız
@Test
public void testDoWork() throws Exception{

  MyTest mytest = new MyTest();

  OtherObj obj = new OtherObj();
  obj.test="mocked Test"; //here you can add any other needed values to obj

  PowerMockito.whenNew(OtherObj.class).withNoArguments().thenReturn(obj);

  String result = mytest.doWork();
  Assert.assertTrue(result.equalsIgnoreCase("mocked Test"));
}
Örnek

Şöyle yaparız. Burada Unit Under Test içinde new'lenen mock nesneyi Mockito ile yaratıyoruz.
@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomerContactDaoImpl.class)//the class creating the new instance
public class CustomerContactDaoImplTest {

    @Mock
    JdbcTemplate jdbcTemplateMock; //YOUR MOCK TO BE INJECTED

    @InjectMocks
    CustomerContactDaoImpl customerContactDaoImpl;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

  @Test
  public void insertCustomerContactTest() throws Exception {
    //Arrange
    Contact contact = ...

    SimpleJdbcCall mockedSimpleJdbcCall = Mockito.mock(SimpleJdbcCall.class);
  
    PowerMockito.whenNew(SimpleJdbcCall.class).withArguments(jdbcTemplateMock)
      thenReturn(mockedSimpleJdbcCall);

    //Act
    customerContactDaoImpl.insertCustomerContact(contact);

    //Assert
    ...
  }
}
Örnek
Elimizde şöyle bir kod olsun.
public class ClassIWantToTest {
    private ClassIWantToMock anotherClass;
    public ClassIWantToTest() {
        //some stuff
        anotherClass = new ClassIWantToMock(); //<-- call constructor to build the field
        //some other stuff
    }
}
Şöyle yaparız. Burada new'lenen mock nesneyi PowerMockito ile yaratıyoruz.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassIWantToTest.class,ClassIWantToMock.class})
public class ClassIWantToTest_Test {
  @Test
  public void myFirstTest() {
    ClassIWantToMock myMock = PowerMockito.mock(ClassIWantToMock.class);
    PowerMockito.whenNew(ClassIWantToMock.class).withAnyArguments().thenReturn(myMock); 
    ClassIWantToTest test = new ClassIWantToTest(); //<-- not mocked
  }
}

12 Aralık 2019 Perşembe

PowerMockito @PrepareForTest Anotasyonu

Giriş
Açıklaması şöyle.
This annotation tells PowerMock to prepare classes for testing. In practice, we indicate the classes for which we want to manipulate bytecode. These annotations are required if we want to create mock of final classes or classes with private, final or static methods.
PowerMockito ve JUnit 5
PowerMockito halen JUnit 5'i desteklemiyor. JUnit 5'ten JUnit 4'e geçince insan bazı hatalar yapabiliyor. Bunları not aldım

1. Eğer test sınıfı public değilse şöyle bir hata alınır
"Test class should have public zero-argument constructor". 
Alakası yok. Test sınıfını public yapın yeter.

2. Eğer test metodu public değilse şöyle bir hata alınır
"Method foo should be public". 

3. @Test anotasyonu için JUnit 4 kullandığımız şu import lazım.
org.junit.Test
Eğer el alışkanlığı şunu import edersek
org.junit.jupiter.api.Test
Şöyle bir hata alırız.
org.powermock.api.mockito.ClassNotPreparedException

Örnek
Bazı kodlarda bu anotasyon boş bırakılıyor. Bence bu gereksiz.
@RunWith(PowerMockRunner.class)
@PrepareForTest({})
public class StudentServiceTest {
  ...
}
Örnek
Şöyle yaparız.
@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooTest {

   private Foo Foo; 

  @Before
  public void initMocks() throws Exception {
    fooMock = PowerMockito.spy(new Foo(...));
    PowerMockito.doNothing().when(foo, "initialize");    
  }
  
}