简体   繁体   English

如何使用JUnit和Mockito测试void方法?

[英]How do I test a void method using JUnit and Mockito?

My void method changes boolean variable value in the class. 我的void方法更改了类中的boolean变量值。 How do DI check that? DI如何检查?

I have: 我有:

  • mocked class object 模拟类对象
  • called the method with proper parameters 用适当的参数调用方法
  • checked the instance variable 检查了实例变量

But that doesn't change the value of instance variable. 但这不会改变实例变量的值。 How do I do this? 我该怎么做呢?

ReferenceLettersBean rf = Mockito.mock(ReferenceLettersBean.class);
     rf.setBoolcheck(false);

Mockito.doNothing().when(rf).checkForDuplicates(anyString(),     anyString(), anyString());
         rf.checkForDuplicates("abcd@emal.com","abd@gmail.com","abcd@gmail.com");
assertEquals(true,rf.getBoolcheck());
  • DON'T mock the class you are trying to test. 不要嘲笑你想要测试的课程。
  • DO mock the classes that interact with the class you are trying to test. 模拟与您要测试的类交互的类。

If you want to test that a field in aa class changes from false to true, what you really want to do is something like (I don't have your actual constructor, I'm just guessing): 如果你想测试一个类中的字段从false变为true,你真正想要做的就是(我没有你的实际构造函数,我只是猜测):

SomeDependency dependency = mock(SomeDependency.class);

// Make a REAL ReferenceLettersBean
ReferenceLettersBean bean = new ReferenceLettersBean(dependency);

// now make your test
rf.checkForDuplicates("abcd@emal.com","abd@gmail.com","abcd@gmail.com");
assertEquals(true,rf.getBoolcheck());

This boolean value seems to be an internal state. 这个布尔值似乎是一个内部状态。 This is not something you can directly test with unit tests unless you make it public or it is detectable by influencing the behavior of another method. 除非您将其公开或通过影响另一种方法的行为来检测,否则您无法直接使用单元测试进行测试。

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

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