Search code examples
javajmockit

Possible to mock fields annotated with @Context in JMockit?


I have the following field in a class under test:

class ClassUnderTest {

  @Context
  public javax.ws.rs.core.SecurityContext securityContext;

  public void someMethod() {
    securityContext.getUserPrinciple(); // securityContext is always null here - never mocked
  }
}

But I cannot get JMockit to mock it using expectations or the MockUp approach, in both cases in the class under test securityContext is always null?

@Test
public void usingExpectations() {
  new Expectations() {
    @Mocked
    SecurityContext mockSecurityContext;
    @Mocked
    Principal mockPrinciple;
    {
      mockSecurityContext.getUserPrincipal();
      result = mockPrinciple;

      mockPrinciple.getName();
      result = username;
     }
  };

  new ClassUnderTest().someMethod();
}

@Test
public using usingMockUp() {
  new MockUp<SecurityContext>() {
    @Mock
    Principle getUserPrincipal() {
      // return something   
    };
  }
  new ClassUnderTest().someMethod();
}

Solution

  • Your test code is not doing anything to have the securityContext field set, so it remains null.

    JMockit has features for that, though. You can either set the field explicitly by calling Deencapsulation.setField(...), or let JMockit do it automatically by using the @Tested and @Injectable annotations. For details and examples, please check the documentation.