4

我正在努力学习 Mockito 来对应用程序进行单元测试。以下是我当前尝试测试的方法示例

public boolean validateFormula(String formula) {

    boolean validFormula = true;
    double result = 0;

    try {
        result = methodThatCalculatAFormula(formula, 10, 10);
    } catch (Exception e) {
        validFormula = false;
    }

    if (result == 0)
        validFormula = false;
    return validFormula;
}

这个方法调用同一个类中的另一个方法,methodThatCalculatAFormula我不想在我 unittest 时调用它validateFormula

为了测试这一点,我想看看这个方法的行为取决于methodThatCalculatAFormula返回的内容。因为它false在为 0 时result返回,如果它是除 0 以外的任何数字,则返回有效,我想模拟这些返回值而不运行实际methodThatCalculatAFormula方法。

我写了以下内容:

public class FormlaServiceImplTest {
    @Mock
FormulaService formulaService;

@Before
public void beforeTest() {
   MockitoAnnotations.initMocks(this);
}

@Test
public void testValidateFormula() {                 

`//Valid since methodThatCalculatAFormula returns 3`    
when(formulaService.methodThatCalculatAFormula(anyString(),anyDouble(),anyDouble(),anyBoolean())).thenReturn((double)3);        
        assertTrue(formulaService.validateFormula("Valid"));    



//Not valid since methodThatCalculatAFormula returns 0
when(formulaService.methodThatCalculatAFormula(anyString(),anyDouble(),anyDouble(),anyBoolean())).thenReturn((double)0);
    assertFalse(formulaService.validateFormula("Not Valid"));
}

但是,当我运行上面的代码时,我assertTruefalse. 我猜我在模拟设置中做错了什么。methodThatCalculatAFormula我将如何通过模拟返回值而不实际调用它来测试上述方法。

4

2 回答 2

4

您要做的不是模拟,而是间谍(部分模拟)。您不想模拟一个对象,而只想模拟一种方法。

这有效:

public class FormulaService {
    public boolean validateFormula(String formula) {

        boolean validFormula = true;
        double result = 0;

        try {
            result = methodThatCalculatAFormula(formula, 10, 10);
        } catch (Exception e) {
            validFormula = false;
        }

        if (result == 0)
            validFormula = false;
        return validFormula;
    }

    public  double methodThatCalculatAFormula(String formula, int i, int j){
        return 0;
    }
}

public class FormulaServiceImplTest {

    FormulaService formulaService;

    @Test
    public void testValidateFormula() {

        formulaService = spy(new FormulaService());
        // Valid since methodThatCalculatAFormula returns 3`
        doReturn((double) 3).when(
                formulaService).methodThatCalculatAFormula(anyString(),
                        anyInt(), anyInt());
        assertTrue(formulaService.validateFormula("Valid"));

        // Not valid since methodThatCalculatAFormula returns 0
        doReturn((double)0).when(
                formulaService).methodThatCalculatAFormula(anyString(),
                        anyInt(), anyInt());
        assertFalse(formulaService.validateFormula("Not Valid"));
    }
}

但是你不应该使用间谍。您应该将类​​重构为两个,以便您可以针对另一个模拟测试一个。

于 2013-03-13T16:21:26.187 回答
0

您不能在 Mocked 类中测试代码。如果你只是模拟它,所有的方法都是存根。

您必须改为监视它。阅读有关如何使用 Spy 的 Mockito 文档。

于 2013-03-13T16:16:46.943 回答