如何使用ejp无状态本地类模拟测试类中的私有静态java.util.prefs.Preferences

时间:2018-10-26 11:22:09

标签: java unit-testing ejb

  

我想使用Mockito编写测试类以测试具有接口的无状态本地ejb。

    public class SampleHandler{

        private static final Logger logger = Logger.getLogger(TLDHandler.class);

        @EJB
        private IMsAgent msAgent;

        public void setMsAgent(IMsAgent msAgent) {
            this.msAgent = msAgent;
        }

    public infoAvailability checkInfoAvailable(String sample){
        final URI url = msAgent.buildUrl(API_PREPEND_URL + sample + "/check");    
    }
}

    @Stateless
    @Local({IMsAgent.class})
        public class MsAgentImpl implements IMsTokenAgent {

        private static final String API_BASE_URL_PROPERTY_NAME = "API_BASE_URL";
        private static final String DEFAULT_API_BASE_URL = "https://stage.url.com/v1";
        private static Preferences preferences = Preferences.systemNodeForPackage(MsAgentImpl.class);

        @Override
        public URI getBaseUrl() {
            return URI.create(preferences.get(API_BASE_URL_PROPERTY_NAME, DEFAULT_API_BASE_URL));
        }
    }
  

我的测试班

@RunWith(MockitoJUnitRunner.class)
public class sampleTest {

    @Mock
    IMsAgent msAgent;

    @InjectMocks
    private SampleHandler sampleHandler = new SampleHandler();

    @Before
    public void setUp() {
      sampleHandler.setMsAgent(Mockito.mock(MsAgentImpl.class));
    }

    @Test
    public void checkInfoTest() throws Exception {
  final infoAvailability response = sampleHandler.checkInfoAvailable("sample");
    }
}
  

当我从sampleTest类控件运行checkInfoTest方法时,将转到SampleHandler类。在该类中,url变量始终返回null值。       调试完我的代码后,再也不会使用MsAgentImpl.getBaseUrl方法。

0 个答案:

没有答案