在when()中将文件传递给JUnit测试



我试图编写单元测试用例,其中我需要通过在单元测试用例类中创建的文件以供使用。我使用@Before创建了这个文件。但是我无法理解如何传递我在单元测试中创建的文件,以便obj将该文件用于进一步执行。

public class Core {
@Bean
public SomeObject obj(){
String fileName = "Some file name";
String r = FileUtils.readFileToString(new File(fileName)); 
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration
public class CoreTest extends TestCase {
File file ;
@Before
public void init() throws IOException {
file = new File("myFile.txt");
file.createNewFile();
}
@After
public void cleanUp()
{
file.delete();
}
@Test
public void testFunction() {
Core obj1 = new Core();
File file = Mockito.mock(File.class);
FileUtils f = Mockito.mock(FileUtils.class);
try {

Mockito.when(f.readFileToString(file)).thenReturn(str); //exception thrown here
SomeObject o = obj1.obj();
} catch (Exception e) {
e.printStackTrace();
}
assertNotNull(obj);

会不会为此
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.

我的理解应该是这样的:

try {
Mockito.doReturn(str).when(f).readFileToString(Mockito.any());
SomeObject o = obj1.obj();
} catch (Exception e) {
e.printStackTrace();
}

因为这样你可以告诉Mockito它必须截取哪个方法调用并用期望的返回值替换。

最新更新