首页 > 解决方案 > 我如何模拟方法,从另一种方法调用一个方法?

问题描述

我是 Mocking 的新手。我有一个我想调用的服务,比如说名字 A,我需要测试一些方法。

@Service
public class A {



private Logger logger = LoggerFactory.getLogger(getClass());

    private final CoreXReader coreXReader;

    @Autowired
    B b;

    @Autowired
    C c;


    @Async
    public void someMethod(Config config) throws Exception {
        pushConfig(config);
    }

    private void pushConfig(Config config) throws Exception {

        String url = config.getBaseurl() + config.getId(); 
        ABCRestClient restClient = new ABCRestClient(url);

            String jobJson = restClient.callRestMethod(HttpMethod.GET, "");

    } 

} 

ABCRestClient 示例

  public class ABCRestClient {
        private Logger logger = LoggerFactory.getLogger(getClass());


        private String url;

        public ABCRestClient(String url) {
            this.url = url;
        }


        public String callRestMethod(HttpMethod method, String payload) throws Exception {
            someresponse="example response";
            return someresponse;
        }
    }

我正在尝试通过创建 mockSpy 进行测试,但它仍然调用它的“callRestMethod”

@RunWith(SpringRunner.class)
@SpringBootTest // (webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

    @Autowired
    private A a;



    private Logger logger = LoggerFactory.getLogger(getClass());

    @Before
    public void prepareMockDataForService() throws Exception {

        ABCRestClient apiClient = new ABCRestClient(config.getBaseurl() + config.getId() );
        ABCRestClient apiClientSpy=Mockito.spy(apiClient);

        doReturn(getCallResponse()).when(apiClientSpy).callRestMethod(HttpMethod.GET, "");


    }

    @Test
    public void TestPushConfig() throws Exception {
        a.someMethod(StubDataGenerator.getConfig());

    }

    private String getCallResponse() {
        return "{"msg":"sample response"}";
    }

}

我不确定我在这里做错了什么,为什么它调用实际的callRestMethod因为我已经创建了一个 spy 。

我也试过用这个Mockito.doReturn(getCallResponse()).when(apiClientSpy.callRestMethod(HttpMethod.GET, ""))

另外,如果我使用它Mockito.doReturn()或直接使用这两个语句有什么区别doReturn()吗?就我而言,两者的行为似乎相同。

在我也尝试过这个之前,when().thenReturn(); 但我在某个地方读到了when().thenReturn()当你真正想打电话时使用的东西。如果我的理解有误,请指正。

标签: javajunitmockingmockitojunit4

解决方案


您可以尝试模拟而不是间谍:

   @RunWith(SpringRunner.class)
   @SpringBootTest // (webEnvironment= 
   SpringBootTest.WebEnvironment.RANDOM_PORT)
   public class Test {

    @Autowired
    private A a;



    private Logger logger = LoggerFactory.getLogger(getClass());

    @Before
    public void prepareMockDataForService() throws Exception {

        ABCRestClient apiClientSpy=Mockito.mock(ABCRestClient.class);

        doReturn(getCallResponse()).when(apiClientSpy).callRestMethod(HttpMethod.GET, "");


    }

    @Test
    public void TestPushConfig() throws Exception {
        a.someMethod(StubDataGenerator.getConfig());

    }

    private String getCallResponse() {
        return "{"msg":"sample response"}";
    }
  }

推荐阅读