I have a class like below:
public class Connection{
public boolean isDBConnectionRelativeException(String key) {
Set<String> keySet = new HashSet<>();
keySet.add("key1");
keySet.add("key2");
keySet.add("key3");
if (keySet.contains(key)) {
return true;
}
return false;
}
}
and I don't know how to do unit test with it
I find similar situation in [How to mock the return value of a Map?
but I think it is not a same problem. I try to do it with PowerMockito as below, but it doesn't work
@RunWith(PowerMockRunner.class)
@PrepareForTest({HashSet.class})
public class ConnectionExceptionAspectTest {
private Connection connectionExceptionAspect;
@Before
public void init(){
Mockito.validateMockitoUsage();
connectionExceptionAspect = new Connection();
}
@Test
public void isDBConnectionRelativeExceptionMock() {
Set<String> stringSet = new HashSet<>();
Set<String> clazzSet = spy(stringSet);
try {
PowerMockito.whenNew(HashSet.class).withNoArguments().thenReturn((HashSet) clazzSet);
PowerMockito.when(clazzSet.contains("key")).thenReturn(true);
}catch (Exception e){
e.printStackTrace();
}
assertTrue(connectionExceptionAspect.isDBConnectionRelativeException("key"));
}
}
please help me make a unit test with it!thanks!
**//after edit one time **
In the real situation, Set keySet is constructed with
Set<String> keySet = new HashSet<>();
,keySet.add(element) can't run in test case, it is more complicated. so I just want to mock it to get my result like
PowerMockito.when(keySet.contains("key")).thenReturn(true);
I know PowerMockito can mock a local new variable instance, but I don't know how to do with a local new map instance. I can't find any about this. I am very grateful to all those who are concerned about this issue. My English is terrible to explain my question.
//after edit second time
I know how to mock a POJO local new variable instance, but I don't know how to mock a Set< String >, Map< String,String > etc local new variable instance. I think they are quite different. that's the problem: how to mock a local Set< String >, Map< String,String > etc instance.