FileSystem to FTPFile []?

I just want to know if there is a way to mock the FTPFile array. I am trying to pass a fake FTPFile [] as a parameter to the function I want to check:

protected void indexFolder(FTPClient, FTPFile[], File, FTPFolderAssetSource); 

I use FakeFtpServer to fake, as the name says, my ftp server. This library allows you to fake ftp content this way:

  fileSystem = new WindowsFakeFileSystem(); DirectoryEntry directoryEntry1 = new DirectoryEntry("c:\\"); directoryEntry1.setPermissions(new Permissions("rwxrwx---")); directoryEntry1.setOwner(USER1); FileEntry fileEntry1 = new FileEntry("c:\\data\\file1.txt", CONTENTS); fileEntry1.setPermissionsFromString("rw-rw-rw-"); fileEntry1.setOwner(USER1); fileEntry1.setGroup(GROUP); fileSystem.add(directoryEntry1); fileSystem.add(fileEntry1); ftp = new FakeFtpServer(); ftp.setFileSystem(fileSystem); 

Now, how can I use fileSystem to test my function, which requires FTPFile [] as a parameter?

+4
source share
1 answer

There is nothing special in the FTPFile class that would prevent ridicule. Unfortunately, using Mockito, you cannot mock arrays because they are final.

This sample code should demonstrate the problem:

 import static org.mockito.Mockito.*; import org.junit.Test; public class TestMockArrays { interface Animal { String getName(); } @Test public void testMockArray() { final Animal[] mockArray = mock(Animal[].class); when(mockArray[0].getName()).thenReturn("cat"); when(mockArray[1].getName()).thenReturn("dog"); when(mockArray[2].getName()).thenReturn("fish"); print1st3(mockArray); } public static void print1st3(final Animal[] animals) { System.out.println(animals[0].getName() + " " + animals[1].getName() + " " + animals[2].getName()); } } 

Run it and you will see that this leads to an error message that clearly indicates a problem:

org.mockito.exceptions.base.MockitoException: Cannot mock class [LTestMockArrays $ Animal;

Mokito cannot taunt / spy on: - final classes - anonymous classes - primitive types

The easiest solution is to use an extension for Mockito, such as Powermock , which bypasses certain restrictions for Mockito mocking using bytecode manipulations. You can then create the mock array by adding the following annotations to your junit test class:

 @RunWith(PowerMockRunner.class) // Need to run with Powermock runner @PrepareForTest(FTPFile[].class) // We prepare FTPFile[] class for test because it final 

then in your testing method you will create a Mockito as usual:

 FTPFile[] mockFTPFiles = mock(FTPFile[].class); 
+3
source

Source: https://habr.com/ru/post/1394214/


All Articles