【问题标题】:Mockito - Accessing private/autowired fields for verify()Mockito - 访问用于 verify() 的私有/自动装配字段
【发布时间】:2015-10-19 13:38:32
【问题描述】:

所以我是 Mockito 测试门面的新手。所以基本上我想检查一个 Service 方法是否被调用一次。

这是一个简化的例子

我的服务

public class Service {
    public int myMethod(int index, int number) {
        if (index<4){
            index = index + number;
        }
        return index;
    }
}

我的门面:

public class Facade {

    private Service service;

    public void method(){
        int i = service.myMethod(4, 2);
    }

}

最后是我的测试:

public class FacadeTest {
    @InjectMocks
    private Facade classUnderTest;

    @Mock (name="service")
    private Service service;

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

    @Test
    public void test(){
        verify(classUnderTest, times(1)).service.myMethod(4,2);
    }
}

我知道可以在我的 Facade 中使用 Getter/Setter 方法来返回服务,但我想这样做,但不这样做。

是否有可能以我想要的方式,而不对外观进行任何更改?

当我有一个 Spring 项目并将 @Autowired 用于 Facade 内的服务变量时,有什么不同吗?

谢谢!

【问题讨论】:

  • 将您的测试方法中的classUnderTest 替换为service 并完成。您只能在模拟而不是在测试的类上验证调用(因为它不受 Mockito 控制)。
  • 你不需要任何 getter,因为门面注入和使用的服务是private Service service;。所以你可以访问它,并且可以验证它的方法是否被调用。

标签: spring testing mocking mockito facade


【解决方案1】:

使用@InjectMocks 会将带注释的@Mock 服务注入到您的外观中。 因此,您的测试不需要任何 getter 或 setter。

您似乎忘记在测试中调用方法。 试试这个:

@Test
public void test(){
    classUnderTest.method();
    verify(service, times(1)).service.myMethod(4,2);
}

在您的外观中使用@Autowired 服务不会对您的测试产生影响,因为其中没有使用弹簧。当你运行你的应用程序时,Spring 会注入正确的 bean。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2016-03-23
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2012-06-07
    • 2013-01-08
    相关资源
    最近更新 更多