Why Mockito @InjectMocks might be a thing to avoid?

前端 未结 2 640
予麋鹿
予麋鹿 2021-01-12 08:11

Why @InjectMocks might be a thing to avoid for this kind of test.

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    @Mock
    p         


        
2条回答
  •  走了就别回头了
    2021-01-12 09:06

    Also, some people sugest that dependencies should be added by constructor, not by setters, this way the correct dependecies are guarantied at compile time. See this.

    By using constructors you are forced to limit yourself in the number of components to use as a dependency reducing complexity. (This may not be easy and changes a lot the way to do things in Spring).

    Update: After some time working with dependencies autowired in the constructor I have clearly noted that test are less fragile. I still need to change the tests when dependencies change but the compiler tells me where I should change it and how big the change is. Even better, now I can distinguish between changes to the test to adapt to the new code in compile time and failures added by this code in runtime.

提交回复
热议问题