首页 > 解决方案 > 我如何在这里模拟最终的内部类

问题描述

我正在为其编写 Junits 的类:

public class AImpl implements AInterface {
     public String method1(String id) throws Exception {

     String s = Service.Factory.getInstance().generate(id);
     return s;
  }
}

要使用其 Inner 类实例化的接口:

public interface Service {

    String generate(String var1) throws Exception;

    public static final class Factory {
        private static Service instance = null;

        public Factory() {
        }

        public static final Service getInstance() {
            if (instance == null) {
                instance = (Service)EnterpriseConfiguration.getInstance().loadImplementation(Service.class);
            }

            return instance;
        }
    }
}

我试过 powerMockito 但它不起作用。

@Test
public void generateTest() throws Exception {
   Service.Factory innerClassMock = mock(Service.Factory.class);
   String id= "id";        
   whenNew(Service.Factory.class).withArguments(anyString()).thenReturn(innerClassMock);
   whenNew(innerClassMock.getInstance().generate("hjgh")).withAnyArguments().thenReturn(id);
   id= AImpl.generate("hjgh");
   Assert.assertEquals("id", id);
}

标签: javajunitmockitopowermock

解决方案


如果我能很好地理解您不清晰的代码,您需要这个junit:


@RunWith(PowerMockRunner.class)
@PrepareForTest({Service.Factory.class})
public class AImplTest {

    private Service serviceMock;

    @Before
    public void setUp() {
        PowerMockito.mockStatic(Service.Factory.class);
        serviceMock = Mockito.mock(Service.class);
        PowerMockito.when(Service.Factory.getInstance()).thenReturn(serviceMock);
    }

    @Test
    public void generateTest() throws Exception {
        Mockito.doReturn("mockid").when(serviceMock).generate(Mockito.anyString());
        Assert.assertEquals("mockid", new AImpl().method1("aaa"));
    }
}

这是我的依赖项:


<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.28.2</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 -->
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.4</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.4</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-core -->
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-core</artifactId>
    <version>2.0.4</version>
    <scope>test</scope>
</dependency>

话虽如此,我会更改您的 Service.Factory 类:在这里您需要一个私有构造函数才能正确实现单例模式。


推荐阅读