英文:
Mock result of a hashSet
问题
我对模拟测试不太了解,帮我模拟一下check方法的结果
如果元素已经在hashSet中,则模拟应返回false
附注:我不想要静态测试
```java
class A {
HashSet<String> hash = new HashSet<>();
public boolean check(String str) {
return hash.add(str);
}
}
class ATest {
// 模拟check方法的代码
}
英文:
I am new to mocking help me to mock the result of check method
The mock should return false if the element is already in the hashSet
ps: i don’t want static testing
class A{
HashSet<String> hash=new HashSet<>();
public boolean check(String str){
return hash.add(str);
}
}
class ATest{
//code to mock the check method
}
答案1
得分: 1
假设您正在尝试为 check()
方法编写测试,似乎不需要对该方法进行模拟。让 HashSet 处理条件和响应方式,以帮助您测试 check()
方法。
因此,以下测试应该足够:
A a = PowerMockito.mock(A.class);
@Test
public void testSet() {
boolean result1 = a.check("1stString");
boolean result2 = a.check("1stString");
assertTrue(result1);
assertFalse(result2);
}
但是,如果您感觉有必要出于某种原因模拟该方法并编写测试,您可以编写两个测试,一个用于验证单个字符串,另一个用于验证重复字符串。类似这样:
@Test
public void testSet_singleEntry() {
when(a.check("someString")).thenReturn(true);
boolean result = a.check("someString");
assertTrue(result);
}
@Test
public void testSet_duplicateEntry() {
// 先用字符串填充集合
a.check("someString");
// 现在期望是,如果再次传递相同的字符串,check() 方法应该返回 false
when(a.check("someString")).thenReturn(false);
boolean result = a.check("someString");
assertFalse(result);
}
当您已经知道方法基于条件会给出何种输出时,才模拟方法。换句话说,您了解预期的行为,因此编写模拟存根,定义在调用方法时应该执行什么操作。
英文:
Assuming you are trying to write tests for check() method, it does not seem the method needs to be mocked.
Let the HashSet handle the condition and the response in a way helps you to test the check() method.
So, this test should be enough:
A a=PowerMockito.mock(A.class);
@Test
public void testSet() {
boolean result1=a.check("1stString");
boolean result2=a.check("1stString");
assertTrue(result1);
assertFalse(result2);
}
But if you feel you need to mock[For whatever reason] the method and write tests, you can have two tests, one for verifying with single string and another for verifying duplicate.
Something like this:
@Test
public void testSet_singleEntry() {
when(a.check("someString")).thenReturn(true);
boolean result=a.check("someString");
assertTrue(result);
}
@Test
public void testSet_duplicateEntry() {
//populate the set with the string once
a.check("someString");
//Now the expectation is that the check() method should return false if same string is passed again
when(a.check("someString")).thenReturn(false);
boolean result=a.check("someString");
assertFalse(result);
}
Of course the method param here are hardcoded which you would want to change and populate as per your test design.
Always remember, you mock a method when you already know what kind of output it will give based on conditions. In other words, you know the expected behaviour and thus writing the mock stub defining what to do when the method is called.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论