Java项目中使用Mockito和JUnit进行测试时遇到的问题

问题描述 投票:0回答:1

我在使用mockito和JUnit测试时遇到一些问题,我想测试一种从用户输入获取数据的方法。当我使用

String id = "E833462"
时,测试函数工作正常,但是当我用生成函数替换它时,registerAccountTest() 将在第
when(mockScanner.nextLine()).thenReturn(id, name, bd, role, sex, password);
行被阻塞,我不知道为什么。虽然这两种方式都是一个带有ID的String。我测试了我的生成函数,它仍然可以创建一个随机的唯一 ID。有人可以帮我解决这个问题吗?感谢您阅读我的问题并尝试解决它来帮助我。

这是我的测试方法

@Test
    void registerAccountTest() {
        Employee em = employees.searchById("E160052");

//        String id = "E833462";
        String id = Inputter.generateUniqueId("E", 6, employees);
        String name = "Test";
        String role = "MA";
        String sex = "Male";
        String bd = "08/03/2000";
        String password = "123456";

        String combinedUserInput =
                id + System.lineSeparator() + name + System.lineSeparator() + role + System.lineSeparator() + sex + System.lineSeparator() + bd + System.lineSeparator() + password;
        System.out.println(combinedUserInput);
        InputStream inputStream = new ByteArrayInputStream(combinedUserInput.getBytes());
        System.setIn(inputStream);

        Scanner mockScanner = spy(Inputter.scanner);
        System.out.println("Before when statement");
        when(mockScanner.nextLine()).thenReturn(id, name, bd, role, sex, password);
        System.out.println("After when statement");

        Executor.registerAccount(employees, em);

        Employee emTest = employees.searchById(id);
        assertNotEquals(null, emTest);
        assertEquals(name, emTest.getName());
        assertEquals(bd, emTest.getBirthdate().format(Inputter.formatterHalf));
        assertEquals(role, emTest.getRole());
        assertEquals(sex, emTest.getSex());

        employees.deleteOne(emTest);
    }

这是我在Inputter类中生成Id函数

public class Inputter {
    public static Scanner scanner = new Scanner(System.in);
    public static String generateUniqueId(String prefix, int len, ObjectList ol) {
        String id;

        do {
            int num = (int) random.nextDouble(Math.pow(10, len));
            id = prefix + String.format("%03d", num);
        } while (!Objects.isNull(ol.searchById(id)));

        return id.trim();
    }
}
java unit-testing junit mockito java.util.scanner
1个回答
0
投票

spy
调用不会更改
Scanner
对象,它会创建一个包装器。该包装器仅存在于您的测试中。您需要替换类
Scanner
中的
Inputter
。在
@BeforeEach
中执行此操作最简单,因此您可以在
@AfterEach
中恢复它。

private Scanner originalScanner;
private Scanner mockScanner;

@BeforeEach
void mockScanner() {
    originalScanner = Inputter.scanner;
    mockScanner = spy(originalScanner);
    Inputter.scanner = mockScanner;
}

@AfterEach
void resetScanner() {
    Input.scanner = originalScanner;
}

@Test
void registerAccountTest() {
   ...
    System.setIn(inputStream);

    System.out.println("Before when statement");
    when(mockScanner.nextLine()).thenReturn(id, name, bd, role, sex, password);
    System.out.println("After when statement");
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.