在 Mocktio 单元测试中,是否可以测试方法对模拟输入参数的副作用?

问题描述 投票:0回答:1

我在java类中有一个方法(称为路由),它接受某个接口的输入参数(称为规则),并使用一些局部变量调用该输入参数的注册方法并返回void。

我想对路由方法进行单元测试,但我不想传递 Rules 接口的实际实现。

我想将模拟规则作为参数传递给路由方法调用。 例如

@Mock
Rules rules; //mocked interface

@Test
void test1() {
   testCase = new MyClass();
   testcase.routing(Rules);  // returns void
}

是否可以在模拟规则对象中拥有某些状态,并在调用我的路由方法后验证其状态是否发生变化?

我知道一个选择是简单地实现规则接口并完全控制它,但我想知道 Mockito 是否有针对这种情况的开箱即用的东西。

java unit-testing mocking mockito
1个回答
1
投票

您可以这样做,但这将使测试成为集成测试,而不是单元测试。像这样,您不仅要测试

MyClass
,还要测试
Rules
。如果您需要集成测试,那么编写一个集成测试,最好使用真实的实例/实现。

您应该验证与模拟的交互:

@Mock
Rules rules;

@Test
void test1() {
   MyClass testCase = new MyClass();
   testcase.routing(rules);

   verify(rules, times(2)).someMethod();
   //verifies 2 interactions with someMethod()

   verify(rules).anotherMethod("something");
   //verifies 1 invocation of anotherMethod() with parameter value `something`

   verify(rules, never()).lastMethod(any());
   //verifies no invocations lastMethod() regardless of parameter value
}
© www.soinside.com 2019 - 2024. All rights reserved.