【问题标题】:Writing a Junit test for a boolean method with no parameters为没有参数的布尔方法编写 Junit 测试
【发布时间】:2020-07-27 06:07:49
【问题描述】:

我有一个班级,我想为其编写一个 junit 测试。 这个方法没有参数,这个方法可以对应吗?

public class classTobeTested {

    @Self
    SlingHttpServletRequest request;

    static final String keyword = "hello";

    public boolean isActive() {
        boolean check;
        String pathChecker;
        pathChecker = (request.getRequestURL()).toString();
        check= pathChecker.contains(keyword);

        return check;

    }

}

这就是我心目中的测试类

@RunWith(MockitoJUnitRunner.class)
public class testclasstobetested {


    @Test
    public void TestclassTobeTested() throws Exception{
        classTobeTested  CTT = new classTobeTested();

        assertFalse(CTT.isActive("hello how are you"));
    }

}

我知道我的方法不带参数,但在方法内声明了字符串。 如何正确使用 assertFalse 来测试非参数方法。

【问题讨论】:

  • 这与你的问题无关,但你看看你的类/方法的命名。通常,类名应以大写开头,而方法名应以小写开头。如需进一步阅读,请参阅geeksforgeeks.org/java-naming-conventions
  • 同意,为了一些隐私,我更改了课程的名称,

标签: java unit-testing junit


【解决方案1】:

使用注解和 Junit4 你可以这样做:

@RunWith(MockitoJUnitRunner.class)
public class testclasstobetested {

    @InjectMocks
    private classTobeTested CTT;

    @Mock
    private SlingHttpServletRequest request;

    @Test
    public void TestclassTobeTested() throws Exception{
        when(request.getRequestURL()).thenReturn(new StringBuffer("hello how are you"));

        assertFalse(CTT.isActive());
    }

}

【讨论】:

  • 编译失败no suitable method found for thenReturn(java.lang.String)
  • 是不是因为when((request.getRequestURL()).thenReturn没有.toString()?
  • 这是因为request.getRequestURL()方法返回了一个StringBuffer。我更新了我的答案,它现在应该可以工作了。
  • 很好,你花了多长时间才擅长编写 Junit 测试?
  • 若干年 ;) 如果您满意,请接受我的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 2020-08-23
  • 1970-01-01
  • 2016-10-31
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多