简体   繁体   中英

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. I want to test my method using 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.

Your problem is: you wrote hard to test code - by using static and new . 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. Now you can use any kind of mocking framework (like EasyMock or Mokito) to provide an Azure object that (again) returns mocked objects.

For the record: I am not sure where your code is getting getAuthentication() from; 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; and its constructor is private. Which is well, perfectly fair: when you design an API using final is a powerful tool to express intent.

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
  • you enable the new experimental feature within Mockito that allows mocking final classes
  • you turn to PowerMock(ito) or JMockit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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