简体   繁体   English

如何使用Mockito测试Azure ARM API?

[英]How to test Azure ARM API using mockito?

I am working on azure ARM methods like provision VM and list all VM's using java sdk. 我正在研究诸如置备VM的Azure ARM方法,并使用java sdk列出所有VM。 I want to test my method using mockito. 我想使用Mockito测试我的方法。 How can I do that without making original call to azure. 我如何做到这一点,而不必先发出天蓝色的电话。

public class ListAllVM{
    public static Azure azure = null;
    public void listAllVM() {
    azure = getAuthentication();
    try {
        int i = 0;
        for (VirtualMachine VM : azure.virtualMachines().list()) {
            System.out.println(++i +
                    " \n VM ID:-" +  VM.id() +
                    " \n VM Name:-" +  VM.name() +
                    "\n");
        }
    } catch (CloudException | IOException | IllegalArgumentException e) {
        log.info("Listing vm failed");      }
  }
}

I am facing problem while getting mock list of vm. 获取虚拟机列表时遇到问题。 How to mock external API class. 如何模拟外部API类。

Your problem is: you wrote hard to test code - by using static and new . 您的问题是:您编写了很难测试的代码-使用staticnew A quick suggestion how to do things differently: 快速建议如何做不同的事情:

public class AzureUtils {
  private final Azure azure;

  public AzureUtils()  { this (  getAuthentication(); }
  AzureUtils(Azure azure) { this.azure = azure };

  public List<VM> getVms() {
     return azure.virtualMachines.list();
  }

In my version, you can use dependency injection to insert a mocked version of Azure.class. 在我的版本,你可以使用依赖注入 插入 Azure.class的嘲笑版本。 Now you can use any kind of mocking framework (like EasyMock or Mokito) to provide an Azure object that (again) returns mocked objects. 现在,您可以使用任何一种模拟框架 (例如EasyMock或Mokito)来提供一个Azure对象,该对象将再次返回模拟对象。

For the record: I am not sure where your code is getting getAuthentication() from; 作为记录:我不确定您的代码从哪里获取getAuthentication() so unless this is a static import; 因此,除非这是静态导入; something is wrong with your code in the first place. 首先,您的代码出了点问题。

In other words: you want to learn how to write testable code; 换句话说:您想学习如何编写可测试的代码; for example by watching these videos . 例如通过观看这些视频

On the other hand one comment says that the Azure class is final; 另一方面,有一条评论说Azure类是最终的。 and its constructor is private. 它的构造函数是私有的。 Which is well, perfectly fair: when you design an API using final is a powerful tool to express intent. 很好,这很公平:使用final设计API时,这是表达意图的强大工具。

Coming from there, you are actually pretty limited to: 从那里来的您实际上实际上仅限于:

  • as written above: you create an abstraction like AzureUtils - this way you can at least shield your own code from the effects from the design decisions by Microsoft 如上文所述:您可以创建类似于AzureUtils的抽象-这样,您至少可以保护自己的代码免受Microsoft设计决策的影响
  • you enable the new experimental feature within Mockito that allows mocking final classes 您可以在Mockito中启用新的实验功能,该功能可以模拟最终课程
  • you turn to PowerMock(ito) or JMockit 您转向PowerMock(ito)或JMockit

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

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