测试方法的最佳方法';s与JUnit和Mockito的结果

测试方法的最佳方法';s与JUnit和Mockito的结果,junit,mockito,tdd,assert,design-guidelines,Junit,Mockito,Tdd,Assert,Design Guidelines,我正在尝试测试该方法: @Override public boolean test(Apple apple) { if (apple == null) { return false; } return "green".equals(apple.getColor()); } 我的第一个猜测是通过以下方式进行测试: package io.warthog.designpatterns.behaviorparameteri

我正在尝试测试该方法:

@Override
    public boolean test(Apple apple) {
        if (apple == null) {
            return false;
        }
        return "green".equals(apple.getColor());
}
我的第一个猜测是通过以下方式进行测试:

package io.warthog.designpatterns.behaviorparameterization.impl;

import io.warthog.designpatterns.behaviorparameterization.Apple; import org.junit.Test;

import static org.mockito.Mockito.when;

public class AppleGreenColorPredicateTest {

    private AppleGreenColorPredicate classUnderTest = new AppleGreenColorPredicate();

    @Test
    public void test_WithGreenApple_ReturnsTrue() {
        Apple apple = new Apple();
        apple.setColor("green");
        when(classUnderTest.test(apple)).thenReturn(true);
    }

}
但它给了我一个错误信息:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when()需要的参数必须是“模拟的方法调用”。 例如: when(mock.getArticles())。然后返回(articles)

所以我最终做了:

package io.warthog.designpatterns.behaviorparameterization.impl;

import io.warthog.designpatterns.behaviorparameterization.Apple; import org.junit.Assert; import org.junit.Test;

public class AppleGreenColorPredicateTest {

    private AppleGreenColorPredicate classUnderTest = new AppleGreenColorPredicate();

    @Test
    public void test_WithGreenApple_ReturnsTrue() {
        Apple apple = new Apple();
        apple.setColor("green");
        Assert.assertEquals(true, classUnderTest.test(apple));
    }

}
这里的问题是,您建议何时使用Mockinto.when()方法,何时使用Assert.equals()


任何帮助都将不胜感激

我会遵循XP规则,做可能可行的最简单的事情。您不需要模拟任何东西,所以直接使用对象即可

private AppleGreenColorPredicate classUnderTest;

@Before
public void setUp() {
    classUnderTest = new AppleGreenColorPredicate();
}

@Test
public void nullTest() {
    assertFalse(classUnderTest.test(null));
}

@Test
public void green() {
    Apple a = new Apple();
    a.setColor("green");
    assertTrue(classUnderTest.test(a));
}

@Test
public void notGreen() {
    Apple a = new Apple();
    a.setColor("red");
    assertFalse(classUnderTest.test(a));
}

在你的mockito代码中,你似乎在模仿你正在测试的东西,也就是说,你不会在你的代码中发现任何问题,因为你的测试只调用mock。这给人一种虚假的安全感。只有在必要的时候才嘲笑。模拟被测类的依赖关系,而不是实际的被测类。

感谢Robert对此主题的见解。回答得很好。