Mockito named()。willReturn()返回零星结果

时间:2018-08-22 07:59:20

标签: spring unit-testing testing mockito

我正在测试使用嘲讽所有1.10.19和spring-boot-starter-parent 2.0.4.RELEASE的简单逻辑。我有一项服务,该服务确定上传的文件是否具有相同的商店代码。如果已经存在,则抛出IllegalArgumentException

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
    }
}

我模拟了cutoffParser.parse(),以便它返回其中包含两个元素的ArrayList<CutOff>

@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);
    }
}

但是我遇到的行为是零星的。该测试会不时通过。在调试过程中,有时会得到大小为2的列表,有时会得到大小为0的列表。这种不可预测的行为的原因是什么?

我肯定错过了一些东西。我们非常感谢您的帮助。

P.S。使用IntelliJ Idea和Ubuntu终端的情况相同。

0 个答案:

没有答案