【问题标题】:Pass a file to JUnit test in when()在 when() 中将文件传递给 JUnit 测试
【发布时间】: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


【解决方案1】:

根据我的理解应该是这样的:

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

因为这样你告诉 Mockito 它必须拦截哪个方法调用并用所需的返回值替换。

【讨论】:

    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多