简体   繁体   中英

Injected Mock behavior not used in constructor

Using Mockito annotations ( MockitoJUnitRunner.class , @InjectMocks and @Mock ):

@RunWith(MockitoJUnitRunner.class)
public class TagRepositoryTest {

    @InjectMocks
    private TagRepository repository;

    @Mock
    private SetupDetails setupDetails;

    ....
}

I have the test target class using the injected dependency in the constructor:

public class TagRepository {

    private final Collection<Tag> tags;

    @Autowired
    public TagRepository(SetupDetails setupDetails) {
        this.tags = Arrays.asList(
                new Tag("name", setupDetails.getSourceId()),
                ...
        );
    ...
}

And I am currently stubbing the method call in @Setup or inside @Test with when() :

when(setupDetails.getSourceId()).thenReturn("1");

This is not working as expected. Mockito seems to only stub the method call after the @InjectMocks TagRepository constructor is called, resulting in a null beeing returned instead of "1" .

Is there a way to get the stub ready before the constructor is called (using Mockito annotations)?

The only way I am being able to work around this is trying to control the order Mockito setups this scenario giving up on Mockito annotations:

public void setUp() {
    setupDetails = mock(SetupDetails.class);
    when(setupDetails.getDbId()).thenReturn("1");

    repository = new TagRepository(setupDetails);
}

Indeed this is the case and your "work around" is the way to go. Some will argue that this is a good practice as your test will not compile when you introduce more members to your class under test, as you'll also add them to the constructor.

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