mercredi 21 août 2019

Can't create an instance of Attribute for a unit test

I am using an API that has a method that fetches some data from a remote server. The method usage is like this:

Attribute a = obj.getRemoteAttribute();

The Attribute class is like this

package a.package.outside.my.project;

import java.util.Date;

public class Attribute {
  private String id;
  private String name;
  private Date modifiedAt;
  private String metadata;

  Attribute(String id, String name, Date modifiedAt, String metadata) {
    this.id = id;
    this.name = name;
    this.modifiedAt = modifiedAt;
    this.metadata = metadata;
  }

  public String getId() {
    return id;
  }

  public Date getModifiedAt() {
    return modifiedAt;
  }

  public String getMetadata() {
    return metadata;
  }

  public String getName() {
    return name;
  }
}

I'm trying to create a unit test, mocking this method. I'm with Mockito for that. The test is something like this:

    @Test
    public void getAttributeShouldWork() throws Exception {
        Storage mockStorage = Mockito.mock(Storage.class);
        Attribute attribute = new Attribute("fake", "fakeName", new SimpleDateFormat("dd/MM/yyyy").parse("21/08/2019"), "fake Metadata"); 
        Mockito.when(storage.getAttribute()).thenReturn(attribute);
        // some other stuff
    }

However, the test does not compile - the constructor from Attribute (4º line) is package private and I can't use it in the test. I can't also extend the class - there is no default constructor. There is no factory to create Attribute, no accessible builder class. I also can't change Attribute's code.

So, my question is - how can I create a fake object to use in this test with mocks? I don't want my unit tests depending on network or remote server's availability...





Aucun commentaire:

Enregistrer un commentaire