user710818
user710818

Reputation: 24248

How to in mockito create folder of method call?

Form docs:

   Comparable c=mock(Comparable.class);
    when(c.compareTo(anyInt())).thenReturn(-1);

I would like:

 File tempDir=new File("test");
   Comparable c=mock(Comparable.class);
    when(c.compareTo(anyInt())).thenReturn(tempDir.mkdir());

So will be created real folder (i will use it next private method of class). Does it possible? Thanks.

Upvotes: 0

Views: 2002

Answers (1)

Tim Pote
Tim Pote

Reputation: 28029

It's incredibly unclear what you're trying to accomplish. I'm not at all certain why you want to do something like this in the first place.

As I said in my comment, the reason your current example won't compile is because File.mkdir() returns a boolean and Comparable.compareTo(Comparable) returns an int. You can, however, make this compile if you are mocking a method that returns a boolean, like so:

public class Foo {
  public static void main(String[] args) {
    File file = new File("/tmp/111");
    Bar bar = mock(Bar.class);
    when(bar.isTrue()).thenReturn(file.mkdir());
  }

  public static interface Bar {
    public boolean isTrue();
  }
}

That said, I seriously doubt this will do what you want. The line when(bar.isTrue()).thenReturn(file.mkdir()); actually invokes file.mkdir(). So your directory will be created when you create your mock. In other words, the previous example can (and should) be equivalently written as:

public class Foo {
  public static void main(String[] args) {
    File file = new File("/tmp/111");
    Bar bar = mock(Bar.class);
    boolean dirMade = file.mkdir();
    when(bar.isTrue()).thenReturn(dirMade);
  }

  public static interface Bar {
    public boolean isTrue();
  }
}

Writing it like this would avoid any confusion on when the directory was actually created.

Upvotes: 1

Related Questions