0

So basically, I am trying to write a unit test but my question is do we need to mock every single argument of variable/object? Doesn't this simply defeat the purpose by manually putting the correct values.

public class MainClass{

    public void somefunction(Object obj){
        List<someOtherClass> lists = obj.list;
        for (someOtherClass list:lists){
             System.out.println(list.v1+list.v2);
        }
    }
}

public class SomeClass {

  public String id;    
  public List<SomeOtherClass> list;

}

public class SomeOtherClass {
public String v1;
public String v2;

}

In my test file:

class MainClassTest {
    
    List<SomeOtherClass> list = new ArrayList<>();
    SomeOtherClass list1 = spy(new SomeOtherClass()); // as adviced here: https://stackoverflow.com/questions/33125769/mockito-when-thenreturn-doesnt-work-properly

    @Test
    void someFunction(){
    when(list1.v1).thenReturn("v1");
    // When I do the above line and try to print `list1.v1` I still get null value. 
    }
}
  1. Should I just mock v1 and v2 and then create the list? Which is the correct and more efficient way? I actually have lot of variables and passing null to check NPE is going to be a pain.
harry123
  • 760
  • 1
  • 7
  • 22
  • 1
    As it is, this question doesn't make a lot of sense. What object are you trying to mock? What is the target of the test? Why are you spying on someOtherClass? Also, can you use canonical java names pls? It makes the code a lot easier to read. You can't mock direct access to object state (you shouldn't access another object's state) -- you can only mock methods -- you replace the whole object with a synthetic mock. This approach makes little sense. – Software Engineer Mar 15 '21 at 18:46
  • 1) Please stick to [Java's naming conventions](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html) as lower-case letters are usually used for fields/members/variables but not for classes 2) there is difference between `mock` and `spy` and how you need to setup the mock. Maybe [this answer](https://stackoverflow.com/questions/31413337/mockito-when-then-not-returning-expected-value/31417676#31417676) might shed some light on that topic 3) In a real unit-test, you mock out everything that is not within the scope of your test-subject (= class to test) – Roman Vottner Mar 15 '21 at 18:53

0 Answers0