编写一个针对没有参数的布尔方法的 JUnit 测试。

huangapple go评论72阅读模式
英文:

Writing a Junit test for a boolean method with no parameters

问题

我有一个类我想为它编写一个 JUnit 测试
这个方法没有参数可以相应地进行测试吗

```java
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 来测试没有参数的方法呢?


<details>
<summary>英文:</summary>

I have a class where I want to write a  junit test for. 
This method has no parameters, can this method accordingly? 

public class classTobeTested {

@Self
SlingHttpServletRequest request;

static final String keyword = &quot;hello&quot;;

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

    return check;

}

}


This would be the testing class i had in mind

@RunWith(MockitoJUnitRunner.class)
public class testclasstobetested {

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

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

}

I know my method does not take a parameter but has strings declared inside the method. 
How can i use assertFalse correctly to test a non param method. 

</details>


# 答案1
**得分**: 2

使用注解和Junit4,您可以像这样完成:

```java
@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());
    }

}
英文:

Using annotations and Junit4 you can do it like this:

@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(&quot;hello how are you&quot;));

        assertFalse(CTT.isActive());
    }

}

huangapple
  • 本文由 发表于 2020年7月27日 14:07:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63109529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定