Reputation: 1608
I have a method that performs a test to see if the user is authorized and then has some other logic in it which I want to test, without actually logging in to authorize my user.
So, I have this static method OAuthUtil.retrieveAuthority()
which returns a string, let's say "domain".
My constructor is something like
public ImplService(){
String authority = OAuthUtil.retrieveAuthority();
//do something else
}
And I have another method which is the one I'm actually trying to test, say getList()
.
retrieveAuthority()
in turn can throw aWebApplicationException if the Subject is null, which it will always be, but I want to bypass this completely. So, I want my mock to return something ("domain") instead of throwing an exception. Is that possible?
So, my test is something like this right now, and it fails when the exception is encountered:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class TestMine {
public ImplService impl;
@Before
public void setUp() {
PowerMockito.mockStatic(OAuthUtil.class);
PowerMockito.when(OAuthUtil.retrieveAuthority()).thenReturn("domain");
ImplService impl = new ImplService();
}
@Test
public void getListTest() throws NotFoundException {
Response response = impl.getList();
}
}
Upvotes: 1
Views: 413
Reputation: 395
Yes it's completely possible. You need to add:
@PrepareForTest({OAuthUtil.class})
public class TestMine { //above this line
Upvotes: 2