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

Hiç yorum yok:

Yorum Gönder