我怎么能在这里模拟最终内部 class

How can I mock final inner class here

Class 我正在为其编写 Junits:

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

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

要使用其内部实例化的接口class:

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);
}

如果我理解你的代码不够清晰,你需要这个 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 class:这里你需要一个私有构造函数才能正确实现单例模式。