0

I was writing a test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MedicineHeadServiceTest {

    @Mock
    MedicineHeadRepository medicineHeadRepositoryMock;

    @Mock
    MedicineHead medicineHeadTest;

    @Autowired
    private MedicineHeadService medicineHeadService;

    @Test
    public void buildMedicineId_if_not_in_db_Test() {
        MedicineHead testObj = new MedicineHead();
        testObj.setMedicineName("medicine");
        testObj.setMedicineType(MedicineTypes.PILL);
        when(medicineHeadRepositoryMock.getByMedicineId(any())).thenReturn(isNull());
        String medicineId = medicineHeadService.buildMedicineId(testObj);
        assertEquals("MEDICINE_PILL_0", medicineId);

but I have InvalidUseOfMatchersException... cannot evaluate...toString() on: when(medicineHeadRepositoryMock.getByMedicineId(any())).thenReturn(isNull());

method i want to test:

        StringBuilder medicineId = new StringBuilder();
        medicineId.append(medicineHead.getMedicineName().toUpperCase() + "_" + medicineHead.getMedicineType().name());
        if (medicineHeadRepository.getByMedicineId(medicineId.toString() + "_0") != null) {
            boolean finish = false;
            int counter = 0;
            while (finish != true) {
                if(medicineHeadRepository.getByMedicineId(medicineId.toString() + "_" + counter) == null){
                    finish = true;
                    medicineId.append("_" + counter++);
                } else {
                    counter++;
                }
            }
        } else {
            medicineId.append("_0");
        }
        return medicineId.toString();
    }

Do You know how to fix this ? And do you know how i can run tests faster ? with @RunWith(SpringRunner.class) @SpringBootTest it works but It takes some time start. Thanks in advance

Kamyyylo
  • 13
  • 2
  • Yes, this answered this question, but in my second test i want to return an object and when i write `when(medicineHeadRepositoryMock.getByMedicineId(anyString())).thenReturn(testObj);` when testObj is an instance of objects i want to return it returns 0. Do you know how i can return an instance of this object ? – Kamyyylo Apr 26 '20 at 16:04
  • Nvm i found solution here: https://stackoverflow.com/questions/16426323/injecting-autowired-private-field-during-testing I had to only remove @Autowired and add @RunWith(MockitoJUnitRunner.class) and InjectMocks – Kamyyylo Apr 26 '20 at 16:29

0 Answers0