5

EasyMock 或 Unitils Mock(不支持 Unitils 的 EasyMock)中是否有任何技术可以将模拟直接注入到被测类中?

例如。在 Mockito 中,可以将模拟直接注入到类的成员变量中,

public class TimeTrackerTest {
    @InjectMocks   // Used to create an instance the CUT
    private TimeTrackerBean cut;
    @Mock  // Used to create a Mock instance
    EntityManager em;
    @Before
    public void injectMockEntityManager() {
        MockitoAnnotations.initMocks(this);   // Injects Mocks into CUT
    }
    @Test
    ...
}

可以用 EasyMock 或 Unitils Mock 完成这些事情吗?在 easymock 中,我们需要在 CUT 中使用单独的 setter 方法来支持来自测试的注入。我是对的还是方向注射是可能的?

-谢谢

4

4 回答 4

6

也许这个线程已经死了,但是是的,您现在可以使用带有 @TestSubject、@Mock 标签的 EasyMock 3.2 并使用 @RunWith(EasyMockRunner.class) 运行测试。看到这个写得很好(不是我写的!)的例子:

http://henritremblay.blogspot.ie/2013/07/easymock-32-is-out.html

于 2014-03-21T16:17:31.827 回答
5

我不知道任何可以让您使用 EasyMock 执行此操作的注释,但是,Spring 具有ReflectionTestUtils,它可以让您轻松地对私有字段进行注入,而无需使用 setter 方法。在我切换到 Mockito 之前,我发现这个类非常宝贵。

于 2012-02-06T18:49:49.087 回答
3

Unitils 具有“注入”模块,用于将模拟对象注入测试对象。有关详细信息,请参阅http://unitils.org/tutorial-inject.html

例如:

public class MyServiceTest extends UnitilsJUnit4
{ 
    @TestedObject MyService myService; 
    @InjectIntoByType Mock<MyDao> myDao; 

    @Test
    public void myTestMethod()
    {
        myDao.returns("something").getSomething(); 

        myService.doService();

        myDao.assertInvoked().storeSomething("something"); 
    }
}
于 2012-07-13T18:36:20.470 回答
1

以下将有助于在其字段上注入使用 @Mock 创建的模拟。

EasyMockSupport.injectMocks(cut);

这里 cut 是注入模拟的对象。有关更多信息,请参阅以下链接 http://easymock.org/api/org/easymock/EasyMockSupport.html#injectMocks-java.lang.Object-

于 2017-06-27T10:03:01.897 回答