简体   繁体   English

Mocking static 方法抛出参数错误

[英]Mocking static method throws error with parameters

I have custom Log4j2 appender:我有自定义 Log4j2 appender:

    @Plugin(
            name = "MyAppender",
            category = "Core",
            elementType = Appender.ELEMENT_TYPE)
    public class MyAppender extends AbstractAppender {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(MyAppender.class);
        private final Lock lock = new ReentrantLock();
    
    
        private MyAppender(final String name, final Layout<? extends Serializable> layout ) {
            super(name, null, layout, false, Property.EMPTY_ARRAY);
        }
    
    
        @Override
        public void append(LogEvent event) {
           ....
        }
    
        @PluginFactory
        public static MyAppender createAppender(
                @PluginAttribute("name") String name,
                @PluginElement("Layout") Layout<? extends Serializable> layout){
            if (layout == null) {
                layout = PatternLayout.createDefaultLayout();
            }
            return new MyAppender(name, layout);
        }
}

And i want to mock the createAppenderMethod :我想模拟createAppenderMethod

 try (MockedStatic<MyAppender> mocked = mockStatic(MyAppender.class)) {
            MyAppender appender = Mockito.mock(MyAppender.class);
            mocked.when(() -> MyAppender.createAppender("myAppender", Mockito.any(Layout.class))).thenReturn(appender);
              ....
        }

However this trows然而这

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: MyAppender cannot be returned by toString() toString() should return String org.mockito.exceptions.misusing.WrongTypeOfReturnValue:toString() 不能返回 MyAppender toString() 应该返回 String

I tried to implement toString() method but the error remains the same.我尝试实现toString()方法,但错误仍然存在。

If u use mocked.when(() -> MyAppender.createAppender("myAppender", Mockito.anyObject())).thenReturn(appender);如果你使用mocked.when(() -> MyAppender.createAppender("myAppender", Mockito.anyObject())).thenReturn(appender);

then i recieve:然后我收到:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. org.mockito.exceptions.misusing.MissingMethodInvocationException:when() 需要一个必须是“模拟方法调用”的参数。 For example: when(mock.getArticles()).thenReturn(articles);例如:when(mock.getArticles()).thenReturn(articles);

Why is this happening?为什么会这样? What is the correct way to mock this?嘲笑这个的正确方法是什么? So far this way of mocking static methods worked for me到目前为止,这种 mocking static 方法对我有用

As per my understanding mocking static methods are not good to follow as it challenges the design level decision.根据我的理解 mocking static 方法不好遵循,因为它挑战了设计级别的决策。 Kindly someone guide me if am wrong.如果错了,请有人指导我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM