【问题标题】:How to mock a protected static inner class with PowerMockito如何使用 PowerMockito 模拟受保护的静态内部类
【发布时间】:2016-02-15 23:21:30
【问题描述】:

我有一个公共外部类和一​​个受保护的静态内部类,我需要对其进行模拟以进行单元测试。我们正在使用 Mockito 和 PowerMockito,但在搜索过程中我找不到任何类似的东西。有没有人有任何想法?将内部类重构为在类之外并公开或任何类似的东西现在也是不可能的。

【问题讨论】:

  • 你的内部类的功能如何,它的功能有点稀疏?
  • 没有。可悲的是,它非常详尽。
  • @NicholasPierce 你看到下面的解决方案了吗?

标签: java unit-testing mockito powermockito


【解决方案1】:

给定一个类似于

的结构
public class OuterClass {

    public OuterClass() {
        new InnerClass();
    }

    protected static class InnerClass {
        public InnerClass() {
            throw new UnsupportedOperationException("Muahahahaha!"); // no touchy touchy!
        }
    }
}

...您应该能够执行以下操作

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertNotNull;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class) // delegate test running to PowerMock
@PrepareForTest(OuterClass.class) // mark classes for instrumentation so magic can happen
public class InnerClassTest {

    @Test
    public void shouldNotThrowException() throws Exception { // oh, the puns!
        // make a mockery of our inner class
        OuterClass.InnerClass innerClassMock = mock(OuterClass.InnerClass.class);

       // magically return the mock when a new instance is required
       whenNew(OuterClass.InnerClass.class).withAnyArguments().thenReturn(innerClassMock);

        // yey, no UnsupportedOperationException here!
        OuterClass outerClass = new OuterClass();
        assertNotNull(outerClass);
    }
}

【讨论】:

  • 我确实看到了这个。我很抱歉没有回复你这个问题。这实际上不适用于我正在使用的特定测试用例。遗留代码是紧密耦合的,需要一些额外的东西才能把它放到需要的地方。话虽如此,这个例子帮助我完成了一个完全不同的测试用例,所以我非常感谢你的帮助!谢谢!
  • @NicholasPierce 好消息!非常欢迎您更新说明您真正问题的问题,因为它与我想象的有点不同,发布并接受您的答案作为正确答案。这样,任何最终会遇到你的情况的人都会知道如何绕过它,而我们其他人实际上可能会学到一些新东西。干杯:-)
  • 我现在正在尝试这样做。这是生产代码,因此出于明显的原因,我必须注意发布和不发布的内容。此外,课堂严重失控。我的直接上级和我正在考虑只花几天的时间来重构它,以便子孙后代,所以我至少会记录下它现在的样子,如果我能找到一个体面的方法,我会发布示例和结果。谢谢!
  • 试过了!它的工作原理如 sn-p 中所示,其中在 shouldNotThrowException 中返回了 InnerClass 的模拟。我想知道为什么这不起作用,如果在其他地方需要一个静态内部类的模拟,例如在不同的类中......?
猜你喜欢
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多