簡體   English   中英

如何使用junit和Mockito使用私有方法測試以下類,這里我不能使用powermockito進行私有方法調用

[英]how to test the following class with private methods using junit and Mockito, here i cannot use powermockito for private method call

下面是我的類,我需要在 Junit 和 Mockito 的幫助下測試從公共方法調用的私有方法

public class Context{
    public void doFilter(final ServletRequest req, final ServletResponse resp)
    throws IOException, ServletException
    { 
    final Map<String, String> config = getPrivateMethod((HttpServletRequest) req);
    final Tags tag = factory.buildTags(config);
    } 
    private Map<String, String> getPrivateMethod(final HttpServletRequest req)
    {
    Map<String, String> config = new HashMap<>();
     host = getHost();
     } 
    private String getHost(){
    requestFile.getHost();
    }
}

如果你使用spring-test依賴,你可以像這樣使用ReflectionTestUtilsMockHttpServletRequest

Context context = new Context(); // Create context, or use one defined previously in the test

MockHttpServletRequest servletRequest = new MockHttpServletRequest();
// Populate request values here if needed

Map<String, String> result = ReflectionTestUtils.invokeMethod(context, "getPrivateMethod", servletRequest);
// do assertions on result

這將使用上下文對象,找到名為“getPrivateMethod”的方法,並使用其余參數調用該方法 - 在本例中為servletRequest

如果您不使用spring-test ,則可以使用 Java 反射自己完成此操作。 您將需要創建自己的對象來實現HttpServletRequest以使用,否則您可以傳遞null如果它從未被引用。

Context context = new Context();
MyHttpServletRequest servletRequest = new MyHttpServletRequest(); // This object needs to be created

// Use reflection to get the method with name "getPrivateMethod" and the single argument of HttpServletRequest
Method privateMethod = Context.class.getMethod("getPrivateMethod", HttpServletRequest.class);

// Set the method as accessible
privateMethod.setAccessible(true);

// Invoke the method
Map<String, String> result = (Map<String, String>) privateMethod.invoke(context, servletRequest);
// do assertions on result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM