[英]Mockito - how to inject final field marked as @Mock by constructor when using @Spy and @InjectMocks
I have a special case, where I have to mock some fields and use both @Mock and @Spy for my class, which is under test, because at some tests I need to change behaviour of it's own methods. 我有一个特殊情况,我必须模拟某些字段并在正在测试的类中同时使用@Mock和@Spy,因为在某些测试中,我需要更改其自身方法的行为。 I use @InjectMocks for constructor. 我使用@InjectMocks作为构造函数。 It looks like this: 看起来像这样:
Test class: 测试类别:
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private SomeObject usedAsNonFinal;
@Mock
private SomeObject usedAsFinal;
@Spy
@InjectMocks
private ServiceTest service = new ServiceTest(usedAsNonFinal, usedAsFinal);
@Before
public void setup() {
when(usedAsNonFinal.someMethod(Matchers.any()))
.thenReturn(someObject);
when(usedAsFinal.someMethod(Matchers.any()))
.thenReturn(someObject);
doReturn(someObject).when(service).someMethod(Matchers.any());
}
}
Service, which is under test: 服务,正在测试中:
@Service
public class Service {
private SomeObject usedAsNonFinal //injects correctly
private final SomeObject usedAsFinal; //null - not injected
@Autowired
public Service (SomeObject usedAsNonFinal, SomeObject usedAsFinal){
this.usedAsNonFinal = usedAsNonFinal;
this.usedAsFinal = usedAsFinal;
}
//some methods to mock depending on test
}
The problem is - as commented in code - that final field is not getting injected and it's null. 问题是-正如代码中所注释的-最终字段没有注入并且为空。 When I remove final keyword it gets injected correctly and all tests are working as expected. 当我删除final关键字时,它将正确注入,并且所有测试均按预期进行。 I tried some tricks from other topics - also using reflection, but nothing seems to be workking in this particular case. 我尝试了其他主题的一些技巧-也使用了反射,但是在这种情况下似乎没有任何作用。
Did you try don't instantiate ServiceTest
in test? 您是否尝试过不要在测试中实例化ServiceTest
?
@InjectMocks should do it for you. @InjectMocks应该为您做到这一点。 Try just 尝试一下
@Spy
@InjectMocks
private ServiceTest service;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.