mercredi 22 août 2018

Mockito given().willReturn() returns sporadic result

I am testing a simple logic using mockito-all 1.10.19 and spring-boot-starter-parent 2.0.4.RELEASE. I have a service, which determines whether the uploaded file has the same store codes or not. If it has, IllegalArgumentException is been thrown:

public class SomeService {

    private final CutoffRepository cutoffRepository;
    private final Parser<Cutoff> cutoffParser;

    public void saveCutoff(MultipartFile file) throws IOException {
        List<Cutoff> cutoffList = cutoffParser.parse(file.getInputStream());
        boolean duplicateStoreFlag = cutoffList
            .stream()
            .collect(Collectors
                    .groupingBy(Cutoff::getStoreCode, Collectors.counting()))
            .values()
            .stream()
            .anyMatch(quantity -> quantity > 1);
        if (duplicateStoreFlag) {
            throw new IllegalArgumentException("There are more than one line corresponding to the same store");
        }
        //Some saving logic is here
    }
}

I mock up cutoffParser.parse() so, that it returns ArrayList<CutOff> with two elements within it:

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

    @Mock
    private CutoffRepository cutoffRepository;

    @Mock
    private Parser<Cutoff> cutoffParser;

    @InjectMocks
    private SomeService someService;

    @Test(expected = IllegalArgumentException.class)
    public void saveCutoffCurruptedTest() throws Exception {
        Cutoff cutoff1 = new Cutoff();
        cutoff1.setStoreCode(1);
        Cutoff cutoff2 = new Cutoff();
        //corruption is here: the same storeCode
        cutoff2.setStoreCode(1);
        List<Cutoff> cutoffList = new ArrayList<>();
        cutoffList.add(cutoff1);
        cutoffList.add(cutoff2);
        MockMultipartFile mockMultipartFile = new MockMultipartFile("file.csv", "file".getBytes());
        //here what I expect to mock up a response with the list
        given(cutoffParser.parse(any())).willReturn(cutoffList);
        someService.saveCutoff(mockMultipartFile);
    }
}

But the behavior I encounter is sporadic. The test is passed from time to time. During debugging I sometimes get list of size 2, sometimes get list of size 0. What is the reason of such an unpredictable behavior?

I am definitely missing something. Any help is highly appreciated.

P.S. the same situation using IntelliJ Idea and Ubuntu terminal.

Aucun commentaire:

Enregistrer un commentaire