【发布时间】:2021-10-13 11:19:34
【问题描述】:
我正在尝试编写单元测试用例,其中我需要传递在单元测试用例类中创建的文件以供使用。我已经使用@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'.
【问题讨论】:
-
确保将模拟对象传递给 obj 方法,否则在该方法中使用的 FileUtils 将充当不同的变量。
标签: java junit spring-test