Я хочу проверить следующий метод.Так как Paths - последний класс, я использовал powermock.
@Service
public class MyLoader {
public String load(String p) throws IOException {
Path aPath = Paths.get(p);
return IOUtils.toString(spreadsheetFilePath.toUri(), StandardCharsets.UTF_8);
}
}
Мой тестовый пример:
@RunWith(PowerMockRunner.class)
public class MyTest {
MyLoader myLoader = new MyLoader();
@Test
public void loadTest() throws IOException {
Paths mockPaths = PowerMockito.mock(Paths.class);
URI mockURI = PowerMockito.mock(URI.class);
Path path = mock(Path.class);
IOUtils ioUtils = mock(IOUtils.class);
when(path.toUri()).thenReturn(mockURI);
when(mockPaths.get(anyString())).thenReturn(path); // Error here with anyString()
when(ioUtils.toString(mockURI, anyString())).thenReturn("test");
String testPathStr = myLoader.load("test");
assertThat(testPathStr, is("test"));
}
}
Я получаю исключение:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at com.MyTest.loadTest(MyLoader.java:20)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
Я пробовал много разных способов, но получал разные типы исключений.Я хочу знать для такого простого метода, как лучше написать контрольный пример с мокито.