I am new to mockito. Spent more than a day now, trying to figure out how this works. This is my last resort.
I have a class as follows:
class Check{
//Map<String, Long> map1 = new HashMap<String, Long>();
//Map<String, Long> map2 = new HashMap<String, Long>();
boolean myLocalMethod(String key, Map<String, Long> map1){
if(map1.get(key) == null){
map1.put("name", (long)10);
return false;
}
else if(map1.get(key) == 10)
return true;
else
return false;
}
I have a test class as follows:
class TestCheck(){
Check mockTest = mock(Check.class);
@Test // using testng. That's what I like
public void testMyLocalMethod(){
Map<String, Long> map1 = new HashMap<String, Long>();
Assert.assertFalse(mockTest.myLocalMethod("name", map1));
map1.put("name", (long)10);
Assert.assertTrue(mockTest.myLocalMethod("name", map1)); // fails
It will be great if someone can give me some guidance here. Thanks in advance!
When you ask Mockito to mock a class, it overrides your existing implementation. Internally, it defines a new class, which at a basic level would look something like this, if you did it explicitly and don't add any additional behaviour using when
or similar:
class MockCheck extends Check {
@Override
void myLocalMethod(String key) {}
}
ie calling myLocalMethod
doesn't actually invoke the parent class' version of myLocalMethod
.
If you want to use your implementation of Check
, just instantiate it like a regular object:
Check mockTest = new Check();
As others mentioned, a mock object will not use your actual implementation. But, you can use a Spy
object to verify behaviors, while using your actual implementation, see Spying on real objects
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.