您的单元测试类应该有 @MockStaticEntityMethods 注释。
只是想为@migue 的上述答案添加更多细节,因为我花了一段时间才弄清楚如何让它工作。网站http://java.dzone.com/articles/mock-static-methods-using-spring-aspects确实帮助我得出了下面的答案。
这是我通过测试类注入实体管理器所做的。首先用 @MockStaticEntityMethods 注释你的测试类并创建 MockEntityManager 类(这是一个只实现 EntityManager 接口的类)。
然后您可以在 ServiceExampleTest 测试类中执行以下操作:
@Test
public void testFoo() {
// call the static method that gets called by the method being tested in order to
// "record" it and then set the expected response when it is replayed during the test
Foo.entityManager();
MockEntityManager expectedEntityManager = new MockEntityManager() {
// TODO override what method you need to return whatever object you test needs
};
AnnotationDrivenStaticEntityMockingControl.expectReturn(expectedEntityManager);
FooService fs = new FooServiceImpl();
Set<Foo> foos = fs.getFoos();
}
这意味着当您调用 fs.getFoos() 时, AnnotationDrivenStaticEntityMockingControl 将注入您的模拟实体管理器,因为 Foo.entityManager() 是一个静态方法。
另请注意,如果fs.getFoos() 调用实体类(如 Foo 和 Bar)上的其他静态方法,它们也必须指定为本测试用例的一部分。
例如,Foo 有一个名为“getAllBars(Long fooId)”的静态查找方法,当调用 fs.getFoos() 时会调用该方法,那么您需要执行以下操作才能使 AnnotationDrivenStaticEntityMockingControl 工作。
@Test
public void testFoo() {
// call the static method that gets called by the method being tested in order to
// "record" it and then set the expected response when it is replayed during the test
Foo.entityManager();
MockEntityManager expectedEntityManager = new MockEntityManager() {
// TODO override what method you need to return whatever object you test needs
};
AnnotationDrivenStaticEntityMockingControl.expectReturn(expectedEntityManager);
// call the static method that gets called by the method being tested in order to
// "record" it and then set the expected response when it is replayed during the test
Long fooId = 1L;
Foo.findAllBars(fooId);
List<Bars> expectedBars = new ArrayList<Bar>();
expectedBars.add(new Bar(1));
expectedBars.add(new Bar(2));
AnnotationDrivenStaticEntityMockingControl.expectReturn(expectedBars);
FooService fs = new FooServiceImpl();
Set<Foo> foos = fs.getFoos();
}
请记住 AnnotationDrivenStaticEntityMockingControl 必须与 fs.getFoos() 调用其静态方法的顺序相同。