英文:
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 = "hello";
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("hello how are you"));
}
}
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("hello how are you"));
assertFalse(CTT.isActive());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论