java - 模拟递归类
问题描述
使用 Spring 2.0.3.RELEASE、JUnit Jupiter 5.7.0、Mockito 3.3.3
尝试测试 Class01 类的方法 method01:
public class Class01 {
private RestConnector con;
public Class01(){
con = RestConnector.getInstance();
}
public Response method01(String x) {
Class01 example = new Class01();
String x = example.isAuthenticated();
// more stuff after this
}
public String isAuthenticated() throws IOException {
// I do stuff
return "a string";
}
}
在测试课上试过
public class Class01Test{
@Mock private Class01 class01Mock;
@Spy @InjectMocks private Class01 class01;
@Test
public void test() throws Throwable {
doReturn("I returned").when(class01). ??? stuck here .. always goes into the isAuthenticated method
Response result = class01.method01("a string");
}
}
目前测试总是运行真正的方法isAuthenticated。如何为方法method01中的字段示例设置模拟,以便执行跳过进入方法isAuthenticated?
解决方案
尝试测试 Class01 类的方法 method01
那么你就不需要模拟了。
@Test
public void test() throws Throwable {
Class01 c = new Class01();
Response expected = ... ;
assertEquals(c.method01("input"), expected);
}
如果要将行为注入example
变量,则需要将其移动到字段
public class Class01 {
private RestConnector con;
private Class01 inner;
public Class01(){
con = RestConnector.getInstance();
}
Class01(Class01 c) {
this();
this.inner = c;
}
public Response method01(String x) {
String x = inner.isAuthenticated();
// more stuff after this
}
连同一个模拟
@RunWith(MockitoJunitRunner.class)
public class Class01Test{
@Mock Class01 class01Mock;
@Test
public void test() throws Throwable {
Response expected = ... ;
when(class01Mock.isAuthenticated()).thenReture(expected); ... // TODO: Setup
Class01 c = new Class01(class01Mock); // pass in the mock
assertEquals(c.method01("input"), expected);
}
但是,当您似乎只需要时,不清楚为什么需要同一类的嵌套对象this.isAuthenticated()
理想情况下,您还可以模拟RestConnector
推荐阅读
- android - Robolectric 测试无法使用 FragmentScenario 和数据绑定找到框架布局 ID
- qt - Qt 抽象模型 - flags() 函数从未被调用
- c# - RazorPages (Core3.1) 如何使用带有 HTML 输入的 asp-for?
- r - 计算给定单词概率、数千个主题和数百万条推文的主题频率
- security - 如何保护后端不被其他未经授权的应用程序访问
- petapoco - 无效操作。使用 Petapoco FetchAsync 时连接已关闭错误
- javascript - 从第一个文本区域获取价值并在第二个文本区域打印
- python - AWS Sagemaker:传递给 Estimator 的数据格式是什么?
- c++ - 滥用条件变量
- macos - 通过 AppleScript 从 Finder 中的选择中取消选择文件