[英]Unable to go to the method of mocked class
我遇到了 JUnit 测试用例的问题。 出于某种原因,我无法将 go 用于模拟 class 的方法,我不确定为什么会发生这种情况。
import java.util.ArrayList;
import static java.util.UUID.randomUUID;
public class Sample {
protected SomeClass someClass;
public void setVariables(SomeClass someClass) {
this.someClass = someClass;
}
protected UserInfo func(String id){
UserInfo userInfo = someClass.getInfo(id);
// I checked that the someClass is mocked instance
// id is not null
}
}
我什至不会采用以下方法。 我不确定为什么实际上会发生这种情况,然后在上述声明中给了我 NPE。
public class SomeClass{
public UserInfo getInfo(String id) {
// not even going in this function at all
if (id == null || id.isEmpty()) return null;
UserInfo userInfo = null;
try {
// do Something
} catch () {
}
return userInfo;
}
}
class SampleTest{
Sample sample;
SomeClass someclass = mock(SomeClass.class);
UserInfo userinfo = mock(UserInfo.class);
@BeforeEach
void setUp(){
// other initialization
sample = new Sample();
sample.setVariables(someclass);
}
@Test
void func(){
when(someclass.getInfo(randomUUID().toString())).thenReturn(userinfo);
UserInfo userInfo = sample.func(randomUUID().toString());
// comparison using assert
}
}
当声明错误。
when(someclass.getInfo( randomUUID().toString() )).thenReturn(userinfo)
一些可能的解决方案:
var randomUuid = randomUUID().toString();
when(someclass.getInfo(anyString())).thenReturn(userinfo)
when(someclass.getInfo(any())).thenReturn(userinfo)
when(someclass.getInfo(eq(randomUuid))).thenReturn(userinfo)
如果您模拟 SomeClass 的实例,您的getInfo代码将不会被执行,请尝试使用 spy 代替。
SomeClass someclass = spy(SomeClass.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.