如何测试 void 方法为私有变量设置正确的值

发布于 2025-01-15 10:45:53 字数 766 浏览 2 评论 0原文

public class ClassOne {
  
  private String exampleString;
  
  public String getExampleString(){
    return this.exampleString;
  }
  
  public void setExampleString(String exampleString){
    this.exampleString;
  }
}
public class ClassOneTest {

  ClassOne classOne = new ClassOne();

  @Test
  void getExampleStringTest(){
    classOne.setExampleString("test");
    assertEquals("test", classOne.getExampleString());
  }
  
  @Test
  void setExampleStringTest(){
    ClassOne classOneMock = mock(ClassOneMock.class);
    ClassOneMock.setExampleString("test");
    verify(classOneMock, times(1));
  }

我有两种方法,一种设置变量,另一种获取该变量的值。我希望能够通过模拟 set 方法并验证变量集的值是否正确来进行测试。

我尝试使用 ArgumentCaptor,但我不确定我是否理解它足以使用它。

public class ClassOne {
  
  private String exampleString;
  
  public String getExampleString(){
    return this.exampleString;
  }
  
  public void setExampleString(String exampleString){
    this.exampleString;
  }
}
public class ClassOneTest {

  ClassOne classOne = new ClassOne();

  @Test
  void getExampleStringTest(){
    classOne.setExampleString("test");
    assertEquals("test", classOne.getExampleString());
  }
  
  @Test
  void setExampleStringTest(){
    ClassOne classOneMock = mock(ClassOneMock.class);
    ClassOneMock.setExampleString("test");
    verify(classOneMock, times(1));
  }

I have two methods, one which sets a variable and another which gets the value of that variable. I want to be able to test by mocking the set method and verifying that the value of the variable set is correct.

I tried using ArgumentCaptor, but I'm not sure if I understand it enough to use it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文