首页 > 解决方案 > 如何使用 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);

这是正确的还是有其他方法可以检查变量。

标签: javaunit-testingjunitmockitopowermockito

解决方案


推荐阅读