There is no setUp() method. If you use the @Before annotation (junit 4), the method name should be before. If you use the @BeforeEach annotation (junit 5), the method name shold be beforeEach.
Create all mock objects via the @Mock annotation.
If using Junit 4, call MockitoAnnotations.openMocks(this) as the first "thing" in the before method.
Don't use Junit 4, if you can. Instead use Junit 5.
If using Junit 5, annotate the class with @ExtendWith(MockitoExtension.class)
Name the thing-that-is-being-tested "classToTest".
If not using @InjectMocks, instantiate the classToTest object in the before method.
Perform manual mock injection (for example, mock a non-injected logger) in the before method.
Use doReturn(xxx).when(xxx).xxx().
Avoid when(xxx.xxx()).thenReturn(xxx).
If 100% of your test methods will "use" one stubbed method, stub it in the before method.
For all other stubbing, perform stubbing in each test.
If many (you determine the number) tests require the same stubbing, create a private method to perform the stubbing and call it in the tests where such stubbing is required.
发布评论
评论(1)
这是我认为的最佳实践:
。如果使用@BeForeEach注释(Junit 5),则方法名称shold be
之前。mockitoAntoNotations.openmocks(this)
作为方法之前的中的第一个“事物”。
@extendwith(mockitoextension.class)注释类
中实例化classtotest对象。
中执行手动模拟注入(例如,模拟未注射的记录器)。
doreturn(xxx)。(xxx).xxx()
。(xxx.xxx())。
Here are my opinionated best practices:
before
. If you use the @BeforeEach annotation (junit 5), the method name shold bebeforeEach
.MockitoAnnotations.openMocks(this)
as the first "thing" in thebefore
method.@ExtendWith(MockitoExtension.class)
before
method.before
method.doReturn(xxx).when(xxx).xxx()
.when(xxx.xxx()).thenReturn(xxx)
.