简体   繁体   English

使用Mockito测试void方法

[英]Testing a void method with Mockito

I have a method like this: 我有这样的方法:

public void someMethod() {
  A a = new A(); // Where A is some class.
  a.setVar1(20);
  a.someMethod();
}

I want to test 2 things: 我想测试2件事:

  1. The value of Var1 member variable of a is 20. a的Var1成员变量的值为20。
  2. someMethod() is called exactly once. someMethod()恰好被调用一次。

I have 2 questions: 我有两个问题:

  1. Are those test objectives correct or should I be testing something else ? 那些测试目标是正确的还是我应该测试其他东西?
  2. How exactly do I test this using Mockito ? 我如何使用Mockito进行测试?

You can't test that using Mockito, because Mockito can't access a local variable that your code creates and then let go out of scope. 您无法使用Mockito进行测试,因为Mockito无法访问您的代码创建的局部变量,然后超出范围。

You could test the method if A was a injected dependency of your class under test, or of the method under test 如果A是被测类或被测方法的注入依赖项,则可以测试该方法

public class MyClass {
    private A a;

    public MyClass(A a) {
        this.a = a;
    }

    public void someMethod() {
        a.setVar1(20);
        a.someMethod();
    }
}

In that case, you could create a mock A, then create an instance of MyClass with this mock A, call the method and verify if the mock A has been called. 在这种情况下,您可以创建一个模拟A,然后使用该模拟A创建MyClass实例,调用该方法并验证是否已调用了模拟A。

With your code, as it is, the only way to test the code is to verify the side effects of calling someMethod() on an A with var1 equal to 20. If A.setVar1() and A.someMethod() don't have any side-effect, then the code is useless: it creates an object, modifies it, and forgets about it. 就您的代码而言,测试代码的唯一方法是验证在var1等于20的A上调用someMethod()副作用。如果A.setVar1()A.someMethod()不这样做如果有任何副作用,那么代码是无用的:它创建了一个对象,对其进行了修改,然后忘记了它。

Use JB Nizet's advice but note that order is important to you: 使用JB Nizet的建议,但请注意顺序对您很重要:

When verifying and order is important, use: 当验证和订购很重要时,请使用:

A mock = mock(A);

new MyClass(mock).someMethod();

InOrder order = inOrder(mock);
order.verify(mock).setVar1(20);
order.verify(mock).someMethod();

(Testing for exactly one invocation is the default in mockito). (mockito中的默认值是测试一次调用是否正确)。

Caution 警告

This kind of test will be tightly coupled to the implementation. 这种测试将与实现紧密结合。 So do this in moderation. 所以要适度地做到这一点。 In general aim for testing state rather than implementation where possible. 通常,目标是测试状态而不是在可能的情况执行

Ad 1) Testing setters usually doesn't make much sense, but if you want to to then surely you have a getter on A to verify that var1 is set to 20? 广告1)测试设置器通常没有多大意义,但是如果您愿意的话,那么您肯定对A有一个吸气剂以验证var1是否设置为20?

Ad 2) You can use @Spy and verify() to test invocations on methods. 广告2)您可以使用@Spyverify()测试对方法的调用。

A spy = spy( a );
verify( spy , times( 1 ) ).someMethod();

Your example code is a bit terse, so my answer is very general - hope you can work with it. 您的示例代码有点简洁,所以我的回答很笼统-希望您可以使用它。

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM