简体   繁体   English

测试使用Mockito重复代码

[英]Tests repeats the code with Mockito

My tests just repeats the code. 我的测试只是重复代码。 For method 方法

public void start(Context context) {
    context.setA(CONST_A);
    context.setB(CONST_B);
    ...
}

I wrote test using Mockito 我用Mockito编写了测试

@Test
public void testStart() throws Exception {
    Context mockContext = mock(Context.class);

    action.start(mockContext);

    verify(mockAction).setA(Action.CONST_A);
    verify(mockAction).setB(Action.CONST_B);
    ...
}

Or for 或为

public void act() {
   state.act();
}

test 测试

@Test
public void testAct() throws Exception {
    State mockState = mock(State.class);
    context.setState(mockState);

    context.act();

    verify(mockState).act();
}

Are such tests useful? 这样的测试有用吗? Such methods need to be tested and how to test them? 这些方法需要进行测试,如何进行测试?

In my opinion, you should not try to have a 100% test coverage in general. 我认为,您一般不应该尝试100%的测试覆盖率。 Having a high test coverage is good, having a perfect coverage is useless and wastes your time. 高测试覆盖率是好的,完美覆盖率是没有用的,会浪费您的时间。 Any method that just sets, gets or delegate work to another method should not be tested, because it will cost you much to write and even more when refactoring. 任何仅设置,获取工作或将工作委托给另一种方法的方法都不应进行测试,因为这将花费您很多钱,甚至在重构时会花费更多。 Finally, it won't add more anti-regression value or any help for anyone using your API. 最后,它不会为使用您的API的任何人增加更多的反回归值或任何帮助。

Prefer testing method with real intelligence, risky or sensitive. 首选具有真实智能,风险或敏感性的测试方法。 The cases you submitted are test more Mockito than your own code. 您提交的案例比您自己的代码更能测试Mockito。 This will take build time and won't help you. 这将花费构建时间,并且不会对您有所帮助。

Personally I don't consider verify() useful at all since it directly tests the implementation instead of the result of your method. 就我个人而言,我根本不认为verify()有用,因为它直接测试实现而不是方法的结果。 This will give you false failures when you change the implementation while the result is still correct. 当您更改实现而结果仍然正确时,这将给您带来错误的失败。

As to whether this is useful: there is no logic to test so no, it's not particularly useful. 至于这是否有用:没有逻辑可以测试,所以没有,它不是特别有用。

According to the comments I left in other answers 根据我在其他答案中留下的评论

public void start(Context context) {
  context.setA(CONST_A);
  context.setB(CONST_B);
  ...
}

should not be tested with Mockito, rather 不应使用Mockito进行测试,而是

@Test
public void testStart() throws Exception {
   Context context = new Context();

   action.start(context);

   assertThat(context.getA(), equalTo(Action.CONST_A));
   assertThat(context.getB(), equalTo(Action.CONST_B));
}

Its not much different, but in comparison with verify it can also get true, if start manages to reach this state without calling a setter or getter. 它的差别不大,但与start相比,如果start设法在不调用setter或getter的情况下达到此状态,则它也可以变为true。

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

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