gpt4 book ai didi

java - Junit 测试失败,如何解决?

转载 作者:行者123 更新时间:2023-11-29 05:30:10 24 4
gpt4 key购买 nike

所以我正在使用 Junit 进行测试,对它来说还很陌生。我正在尝试在名为 SetOfUsers 的类中测试方法,如下所示:

 @Test
public void testFindUserByName() {
System.out.println("findUserByName");
String name = "";
SetOfUsers instance = new SetOfUsers();
User expResult = null;
User result = instance.findUserByName(name);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.

}

所以我想检查在 Bob 中输入的用户名,例如在这样的名称字符串中

String name = "Bob";

因为我在 setOfUsers 类中有一个名为 Bob 的用户。
输出窗口显示此消息

Failed: expected:<null> but was:<Staff name:Bob, Staff pass:abc123>

我该怎么做才能通过?

最佳答案

了解 BDD ,这是使测试易于编写和理解(阅读)的非常好的技术

Test-driven development is a software development methodology which essentially states that for each unit of software, a software developer must:

  • define a test set for the unit first;
  • then implement the unit;
  • finally verify that the implementation of the unit makes the tests succeed.

写得好的测试应该有GivenWhenThen部分

(Given) some context

(When) some action is carried out

(Then) a particular set of observable consequences should obtain

这种风格被称为SpecificationByExample

Given-When-Then is a style of representing tests - or as its advocates would say - specifying a system's behavior using SpecificationByExample.

示例测试

@Test
public void testFindUserByName() {

// given
SetOfUsers instance = new SetOfUsers();

// when
User result = instance.findUserByName("Bob");

// then
assertEquals("Bob", result.getName());

}

很高兴阅读:

关于java - Junit 测试失败,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com