Mockito:“给定...将”返回null而不是答案

时间:2019-05-17 17:00:52

标签: java mockito

我目前正在重组我的单元测试。现在的结构是这样的:

测试班:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest{

    @InjectMocks
    private Service serviceMock;

    private TestData testDataInstance = new TestData();

    @Before
    public void setUp(){
        testDataInstance = new TestData();
        testDataInstance.mockRepository();
    }

    @Test
    public void testSth(){
        ...
    }
}

TestData类:

public final class TestData{
    // this is of course an implemented repo
    @Mock
    public JpaRepository repository;

    public final TestDataObj testDataObj = new TestDataObj();

    public void mockRepositories(){
        MockitoAnnotations.initMocks(this);
        this.testDataObj.mockJpaRepository(jpaRepository);
    }
}

TestDataObj类:

public class TestDataObj{
    public List<DataClass> testData = new LinkedList<DataClass>(...);

    public void mockJpaRepository(JpaRepository repo){
        given(repo.foo(Mockito.any(bar.class))).will(new Answer<List<DataClass>>(){
            public List<DataClass> answer(InvocationOnMock invocation){
                ...
            }
        }
    }
}

如果我执行testSth()方法,则存在JpaRepository Mock,但是foo方法返回null,即使它至少应返回一个空列表。

嵌套存储库模型的想法是可重用性。

问题: 1.服务模拟是在setUp方法之前还是之后创建的? 2.甚至可以像我一样在嵌套对象中调用给定...意志吗?

0 个答案:

没有答案