java如何使用Mockito模拟Spring ApplicationContext的getBean方法,用TestNG编写单元测试?
我正在为下面的课程编写单元测试
待测类别:
public class RandomManager {
@Autowired
private ApplicationContext context;
@Autowired
private ClassA objectA;
public void methodToBeTested() {
objectA.methodToBeVerified(context.getBean(Random.class,"Yaswanth","Yaswanth"));
}
}
以下是测试等级:
public class RandomManagerTest {
@Mock
private ClassA objectA;
@Mock
private ApplicationContext context;
@InjectMocks
private RandomManager randomManager;
@BeforeTest
public void before() {
MockitoAnnotations.initMocks(this);
doReturn(any(Random.class)).when(context)
.getBean(any(Class.class), any(), any());
}
@Test
public void methodToBeTestedTest() {
Random randomObject = new RandomObject("Yaswanth", "Yaswanth");
randomManager.methodToBeTested();
verify(objectA).methodToBeVerified(randomObject);
}
}
当我尝试存根时,上述代码在before方法中失败 应用上下文模拟。我得到以下错误
You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object like any() but the stubbed method signature expect a primitive argument, in this case, use primitive alternatives. when(mock.get(any())); // bad use, will raise NPE when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods cannot be stubbed/verified: final/private/equals()/hashCode(). Mocking methods declared on non-public parent classes is not supported.
有谁能帮我理解我在这个世界上做错了什么 以上代码
注意:我使用的是TestNG和Mockito。我可以延长
AbstractTestNGSpringContextTests
并使用spring-test.xml
,声明我的
beans和autowire应用程序上下文。我觉得这对我来说太过分了
我的用例。我需要模拟applicationContext的getBean方法
# 1 楼答案
这个问题来自
doReturn(any(Random.class))
,在那里你不允许使用any()
。 用一个真实的实例来代替它