Which is the better way to write junit?
className object = new className("test");
when(className.someMethod()).thenReturn(object);
OR
when(className.someMethod()).thenReturn(new className());
CodePudding user response:
This really depends on what you are testing and what you need. Mocking an object is typically done when you need to control the data that is returned from a method. Say you have a class called MyClass and it depends on HttpRequest however you aren't running your server. You would mock up HttpRequest and tell the framework when you call HttpRequest.getRequest() to return a request with certain data in it. The whole point of mocking up objects is to control the data returned to the method you are testing. Then you can make sure your new method is testing correctly because you are controlling the data being put into it.
CodePudding user response:
Both are fine and depend on your use case. With the first approach you still have direct access to the return value.
If you don't need it (e.g. in your assert statement), then the second approach is fine as well.
Simple Java rules. Nothing special.