6 Kasım 2013 Çarşamba

Junit&PowerMock ile static && void metodları mocklamaca & test etmece

Selamlar,

Başlıkta tarif edilen ve tekrar aşağıya yazmaya üşenilen durum için aşağıdaki kodu kullandım, isteyen alabilir ;)

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.math.BigDecimal;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClassEx.class})
public class MyTest
{
protected MyStaticClassEx mockMyStaticClassEx;
protected Request request = new Request();
protected Long longNumber = new Long( 333 );

@Before
public void setUp() throws Exception {
// fill Request object
// ...
mockMyStaticClassEx();
}

public void mockMyStaticClassEx()
{
mockMyStaticClassEx = PowerMockito.mock( MyStaticClassEx.class );
                PowerMockito.when( mockMyStaticClassEx.getId() ).thenReturn( longNumber );
// void method mocking
PowerMockito.doNothing().when( mockMyStaticClassEx ).insertCouponActivity( Mockito.anyLong(), Mockito.anyLong() );

PowerMockito.mockStatic( MyStaticClassEx.class );
                // static method
PowerMockito.when( MyStaticClassEx.getInstance() ).thenReturn( mockMyStaticClassEx );
}

@Test
public void test() throws Exception {

try {
Response response = MainClass.getReq( request );
assertEquals( true, response.result() );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
assertFalse(true);
}

}
}

Hiç yorum yok:

Yorum Gönder