为了账号安全,请及时绑定邮箱和手机立即绑定

基于其他方法返回类型的单元测试布尔方法

基于其他方法返回类型的单元测试布尔方法

倚天杖 2023-08-09 15:26:02
单元测试新手,我正在寻找一种对布尔方法进行单元测试的方法,该方法已通过其他两种方法结果进行验证。 protected boolean isUpdateNeeded(){  return (method1() && method2()); }对于本示例,其他方法如下所示。protected boolean method1() {  return false; }protected boolean method2() {  return true; } 但是如果需要的话,这两种方法可以被覆盖。我不知道现在这是否真的重要所以我的测试背后的想法是这样的。找到一种方法将 true/false 传递给 method1 或 method2 以满足所需的可能结果。@Test public void testCheckToSeeIfUpdateIsNeeded(){    assertTrue('how to check here');    asserFalse('how to check here');   assertIsNull('was null passed?');   }
查看完整描述

2 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

如果另一个类扩展了该类并重写了 method1 和 method2,则开发该类的人员有责任测试更改。


您可以模拟 method1 和 method2,但随后会将类的结构与测试用例耦合起来,从而使以后更难进行更改。


你在这里有责任测试你班级的行为。我看到有问题的方法被称为isUpdateNeeded. 那么让我们测试一下。我将按照我的想象填写课程。


class Updater {

    Updater(String shouldUpdate, String reallyShouldUpdate) {...}

    boolean method1() { return shouldUpdate.equals("yes"); }

    boolean method2() { return reallyShouldUpdate.equals("yes!"); }

    boolean isUpdateNeeded() { ...}

}


class UpdaterTest {

    @Test

    void testUpdateIsNeededIfShouldUpdateAndReallyShouldUpdate() {

        String shouldUpdate = "yes";

        String reallyShouldUpdate = "yes!"

        assertTrue(new Updater(shouldUpdate, reallyShouldUpdate).isUpdateNeeded());

    }

    .... more test cases .....

}

请注意此测试如何在给定输入的情况下断言更新程序的行为,而不是它与某些其他方法的存在的关系。


如果您希望测试演示重写方法时会发生什么,请在测试中子类化 Updater 并进行适当的更改。


查看完整回答
反对 回复 2023-08-09
?
慕沐林林

TA贡献2016条经验 获得超9个赞

所以,例如你有课:


public class BooleanBusiness {


  public boolean mainMethod(){

    return (firstBoolean() && secondBoolean());

  }


  public boolean firstBoolean(){

    return true;

  }


  public boolean secondBoolean() {

    return false;

  }


}

然后你可以编写这样的测试:


import static org.junit.Assert.*;

import static org.mockito.Mockito.when;


import org.junit.Test;

import org.mockito.Mockito;


public class BooleanBusinessTest {


  @Test

  public void testFirstOption() {

    BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);

    when(booleanBusiness.firstBoolean()).thenReturn(true);

    when(booleanBusiness.secondBoolean()).thenReturn(true);

    assertTrue(booleanBusiness.mainMethod());

  }


  @Test

  public void testSecondOption() {

    BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);

    when(booleanBusiness.firstBoolean()).thenReturn(true);

    when(booleanBusiness.secondBoolean()).thenReturn(false);

    assertFalse(booleanBusiness.mainMethod());

  }

}


查看完整回答
反对 回复 2023-08-09
  • 2 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信