未使用doReturn的值

时间:2019-01-10 18:34:37

标签: spring-boot mockito powermock

我使用弹簧靴2。 我搜索以测试外观中的私有方法

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

    @Autowired
    private SamplingsFacade facade;

    @MockBean
    private SamplingsService samplingsService;

    @Test
    public void exampleTest() throws Exception {

        List<Samplings> samplings = new ArrayList<>();
        Samplling sampling = new Samplings();
        ..
        samplings.add(sampling);

        //fake call
        Mockito.doReturn(samplings).when(samplingsService.getSamplingContainingNonCompliantTest());

        //real call
        List<FactoryEmailNCDto> factoryEmails = Whitebox.invokeMethod(facade, "prepareDataNoncompliantSampling");

    }

public List<Samplings> getSamplingContainingNonCompliantTest() {

    return samplingsRepository.findSamplingContainingNonCompliantTest();
}

在立面中

private List<FactoryEmailNCDto> prepareDataNoncompliantSampling() {

    List<FactoryEmailNCDto> factoryEmailNC = new ArrayList<>();

    List<Samplings> samplings = samplingsService.getSamplingContainingNonCompliantTest();

    for (Samplings sampling : samplings) {
        ...
    }

}

为什么当我调试时,采样为空而不是我创建的值

1 个答案:

答案 0 :(得分:0)

Mockito.doReturn(samplings)
    .when(samplingsService.getSamplingContainingNonCompliantTest());

一个潜在的问题是doReturn的格式为doReturn(value).when(mock).method(),而不是doReturn(value).when(mock.method())。后者被认为是不完整的存根。相反,它应该看起来像这样:

Mockito.doReturn(samplings)
    .when(samplingsService)
    .getSamplingContainingNonCompliantTest();

请注意,您的考试可能还有其他问题;您编写的代码期望samplingsServicepublic且非final,而您的getSamplingContainingNonCompliantTest()同样也为public,非{{1} }和非static,但您所拥有的代码示例并未确认这一点。您可能希望通过final方法调用Mockito.validateMockitoUsage(),或使用a @Rule that handles Mockito annotations and cleanup for you