java - 如何使用 Mockito 测试变量的值
问题描述
我正在使用 Mockito 进行测试,我能够模拟方法并验证是否引发了任何异常,如何从我的测试类中断言变量的值
@Service
public class TaskImpl implements Task {
@Autowired
private Utils utils;
@Override
public void doSomeTask(String input, String oldId, String newId) {
Long id = utils.getId(input);
if(id == null) {
throw new CustomException(CustomExceptionCode.ID_DOES_NOT_EXIST);
}
String code = utils.findCode(id, newId);
if(StringUtils.isEmpty(code)) {
throw new CustomException(CustomExceptionCode.NO_CODE_FOR_ID);
}
// some more stuff
}
}
@PowerMockIgnore("org.jacoco.agent.rt.*")
@RunWith(PowerMockRunner.class)
@PrepareForTest({TaskImpl.class})
public class TaskImplTest {
@InjectMocks
private final TaskImpl taskImpl = PowerMockito.spy(new TaskImpl());
@Mock
private Util util;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void doSomeTaskThrowsException() {
when(util.getId(anyString())).thenReturn(null);
exception.expect(CustomException.class);
taskImpl.doSomeTask(anyString(), anyString(), anyString());
}
@Test
public void doSomeTastCodeSuccess() {
when(util.getId(anyString())).thenReturn(1L);
taskImpl.doSomeTask(anyString(), anyString(), "new_id");
// I want to check here how to check {code} value is actually what I am expecting
// Not only string but I want to check other types too
}
}
所以在我的第二次测试中,我想Assert.assertEquals("expected", code);
我能做的一种方法是
String code = util.findCode(id, newId);
然后检查
Assert.assertEquals("expected", code);
这是正确的还是有其他方法可以检查变量。
解决方案
推荐阅读
- android - 我的语言区域翻译文件在正确的目录下无法识别(values-pt-rPT 和 values-pt-rBR)
- python - 创建一个安装 python 模块并运行一些命令的 python 脚本
- javascript - 除非调用 getUserMedia,否则 Safari 13 中不再播放音频
- php - 更改 Woocommerce 购物车商品价格的产品自定义复选框选项
- vim - 使用 pandoc 将 md 转换为 docx
- bash - 使用 AWS 删除超过 1 周的文件的 Bash 脚本
- spring-boot - Spring @Transactional + AspectJ 编译时编织不起作用
- mysql - 在 MySQL 查询中从星期几中排除一天中的时间
- android - 未调用 FirebaseMessagingService 中的 onMessageReceived 方法
- prolog - 如何将匹配元素的索引放入列表中?