0

I am calling this method that returns an empty list..

  public static List<String> getAttribute(@Nullable Subject subject, String key) {

      return Collections.emptyList();
    }

Ignore the simplicity of this method.

I have a test method:

  @Test
  public void testGetRequesterGroupsOnSubject() {
      List<String> testData = new ArrayList<>();
      testData.add("admin");
    mockStatic(SecurityUtils.class);
    mock(SubjectUtils.class);
    doReturn(principalCollection).when(currentSubject).getPrincipals();
    doReturn(testData).when(SubjectUtils.getAttribute(currentSubject, SubjectUtils.ROLE_CLAIM_URI));
    assertEquals(sfa.getRequesterGroups(), new ArrayList<>());
  }

SubjectUtils is the class with the above method. However, even though getAttribute is returning an empty list, shouldn't I expect this to retunr my list of strings? (testData)

Current Error:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at 

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
John Lippson
  • 1,269
  • 5
  • 17
  • 36

1 Answers1

0

I was able to to reproduce your problem and when I use when().thenReturn() instead of DoReturn().When() , the test ran successfully.

@RunWith(PowerMockRunner.class)
@PrepareForTest( SubjectUtils.class )
public class SubjectTest
{
  @Test
  public void testGetRequesterGroupsOnSubject() {
      List<String> testData = new ArrayList<>();
      testData.add("admin");  
      Subject subject = new Subject();      
      PowerMockito.mockStatic(SubjectUtils.class);
      PowerMockito.when(SubjectUtils.getAttribute(subject, "")).thenReturn(testData);
      //PowerMockito.doReturn(testData).when(SubjectUtils.getAttribute(subject, ""));
      assertEquals(SubjectUtils.getAttribute(subject, ""), testData);
  }
}

I couldn't figure out the reason for this behavior. When I search, it seems there is no difference in both approaches for mocked objects.

There is a detailed description for this issue in Unfinished Stubbing Detected in Mockito But I couldn't map it to this case.

pavithraCS
  • 709
  • 6
  • 23