简体   繁体   中英

Should I need to create mock object by passing mock values and pass that to thenReturn or can i just pass new Class() in Junit?

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());

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.

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 (eg in your assert statement), then the second approach is fine as well.

Simple Java rules. Nothing special.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM