【问题标题】:JUnit testing: simulating user inputJUnit 测试:模拟用户输入
【发布时间】:2015-05-26 10:04:04
【问题描述】:

我需要测试一个要求用户输入并向玩家收取输入金额的方法。待测方法:

public void askForBetSize() {
    System.out.println("\nYour stack: " + player.getBalance());
    System.out.print("Place your bet: ");
    bet = Integer.parseInt(keyboard.nextLine()); // = this needs to be simulated
    player.charge(bet);
}

当前的单元测试是:

@Test 
public void bettingChargesPlayerRight() {
    round.setCards();
    round.askForBetSize(); // here I would like to simulate a bet size of 100
    assertEquals(900, round.getPlayer().getBalance()); // default balance is 1000
}

我尝试实现thisthis,但是在测试了以前的类之后,当它开始测试这个方法时,测试停止了运行。

【问题讨论】:

    标签: java unit-testing testing junit


    【解决方案1】:

    您需要的是测试替身,尤其是 Mock 或 Stub。由于您不想使用 Mockito,您可能应该使用您自己的 Stub 实现。 Stub 是一个始终返回相同预设响应的对象。

    我的解决方案(可能已经在其他地方提到过)是重构您的代码,以便您可以将测试替身传递给被测类。

    在我的示例中,我创建了一个接口来表示用户的答案并声明了您的 nextLine() 方法。真实对象将使用 System.in 来捕获用户响应。

    为了测试,我创建了一个这种类型的实例作为匿名内部类,以提供所需的预设答案。

    public interface PlayerInput {
    
        String nextLine();
    
    }
    
    
    public class SimulateSystemInTest {
    
        private Round round;
    
        private PlayerInput keyboardStub = new PlayerInput() {
    
                                            private String bet = "100";
    
                                            @Override
                                            public String nextLine() {
                                                System.out.println(bet);
                                                return bet;
                                            }
                                        };
    
        @Before
        public void setUp() {
            round = new Round(new Player(), keyboardStub);
        }
    
        @Test
        public void bettingChargesPlayerRight() {
            round.setCards();
            round.askForBetSize(); // here I would like to simulate a bet size of 100
            assertEquals(900, round.getPlayer().getBalance()); // default balance is 1000
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      查看 Mockito(存根和模拟),它会对您有所帮助。Mockito

      【讨论】:

      • 当然,你可以编写你的用户行为实现
      • 如果它说如何使用 Mockito 来解决 OP 的问题,这将是一个更好的答案。
      猜你喜欢
      • 2011-09-18
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多