Issue
In my @RestController
I am injecting a Map of @Repositories
that all extend from DataBaseRepository
. See constructor:
@Autowired
public DatasetController(Map<String, DataBaseRepository<?, ?>> reps) {
this.repositories = reps;
}
This works like a charm in normal application, however this is not the case once I try to create a unit test for it (Mocks using Mockito):
@RunWith(MockitoJUnitRunner.class)
public class DatasetControllerTest {
@Mock
private DailyTAVGRepository dailyTAVGRepository; // This extends from DataBaseRepository
@InjectMocks
private DatasetController datasetController;
...
}
In my tests this.repositories
in DatasetController
is null
What am I doing wrong or is this not possible in Unit Tests? Thanks in advance!
Solution
You can use @Before
to create your controller and then have mockito inject mocks for you.
@Before
public void init() {
Map<String, DataBaseRepository> repos = new HashMap<>(); //you can leave this empty or add in a bunch of mocks of your own
datasetController = spy(new DatasetController(repos));
MockitoAnnotations.initMocks(this);
//add your mocked repos to the repos map as needed after mocks are initialized
}
Answered By - Compass
Answer Checked By - Senaida (JavaFixing Volunteer)