简体   繁体   English

使用@Mocked多次模拟同一类时的JMockit行为

[英]JMockit behaviour when mocking same class multiple times using @Mocked

I get different output when mocking a class once and when mocking a class two times in a test. 当一次模拟一个类和一次两次模拟一个类时,我得到不同的输出。 I know that @Mocked mocks all instances of a class but am not sure why mocking more than once affects the output of newly created objects. 我知道@Mocked模拟一个类的所有实例,但是不确定为什么多次模拟会影响新创建对象的输出。 Is this behaviour expected? 这是预期的行为吗?

Test 1. Prints 10 : 测试1.打印10

 @Test
 public void jmockitTest1(@Mocked final Date d1)
 {
       new NonStrictExpectations()
       {{
            d1.getTime(); returns(10L);
       }};

       System.out.println( d1.getTime() );  // prints 10
       System.out.println( new Date().getTime() ); // prints 10 !
 }

Test 2 with second mocked Date. 用第二个模拟日期测试2。 Prints 0 : 打印0

 @Test
 public void jmockitTest2(@Mocked final Date d1, @Mocked final Date d2)
 {
       new NonStrictExpectations()
       {{
            d1.getTime(); returns(10L);
       }};

       System.out.println( d1.getTime() );  // prints 10
       System.out.println( new Date().getTime() ); // prints 0 !
 }

The second test, with Date mocked twice, gets "on-instance" matching by default. 第二个测试(对Date两次模拟)默认情况下获得“实例匹配”。 So, it's as if the expectation was recorded as onInstance(d1).getTime(); 因此,就好像期望记录为onInstance(d1).getTime(); .

This difference in mocking behavior is activated automatically merely as a convenience. 嘲笑行为的这种差异只是为了方便而自动激活。 The only reason to declare multiple mock fields/parameters of the same type in the same test is to have different results from calls to different mocked instances; 在同一测试中声明多个相同类型的模拟字段/参数的唯一原因是,对不同模拟实例的调用会产生不同的结果。 the automatic "on-instance" matching avoids the need to use onInstance(mock) on each of those instances. 自动的“实例匹配”匹配避免了在每个实例上都使用onInstance(mock)的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM