【问题标题】:Testing a method calling a method in the same class which calls a method of service class [duplicate]测试调用服务类方法的同一类中的方法的方法[重复]
【发布时间】:2020-04-05 11:29:03
【问题描述】:

我对 Junit 很陌生,我正在尝试在 Junit 中测试 isApproved 方法。我正在使用 when 和 thenReturn 来嘲笑 isDateValidOfData 方法 Mockito.when(isDateValidOfData(anyLong(), anyString()).thenReturn(true); 这得到了 indexOutOfBounds 异常。这里 serviceClass 在参数匹配器上被调用,因此在数据列表中没有返回任何内容。我只想知道有没有一种方法可以模拟数据并使用 Mockito 和 Junit 对其进行测试。 使用spy获取同一个类的对象调用方法。

MyClass {
        //Service class calls the repository to fetch data. 
        @Autowired
        ServiceClass serviceClass; 

        public boolean isApproved(Long id, String code) {
                // Validation is done on the arguments
                //if id is of a particular type then return true by default
                //if code is in a list already present then continue with the below code or else return true by default. 
                return isDateValidOfData(Long id, String code);
        }

        public boolean isDateValidOfData(Long id, String code) {

                List<Data> data = serviceObject.getData(id, code);
                LocalDateTime eDate = data.get(0).getEDate();
                LocalDateTime rDate = data.get(0).getRDate();
                // check if eDate and rDate is greater than current date, if yes         return true or return false
        }
}

@RunWith(SpringRunner.class)
TestClass {
        @InjectMocks
        MyClass myClass;

        @Test
        public void isApprovedTest() {
                MyClass myClass1 = Mockito.spy(myClass);
                Mockito.when(myClass1.isDateValidOfData(anyLong(), anyString())).thenReturn(true);
                Assert.assertTrue(myClass1.isApproved(1234L, "1234");
        }       
}

【问题讨论】:

  • 我们可以看看你的确切测试吗?
  • @ShaneCreedon,用测试用例更新了我的问题。
  • @Pi53 请edit您的问题包括您拥有的完整源代码。不知道serviceObject() 是什么或isApproved() 是如何实现的。见minimal reproducible example。还包括您收到的完整错误消息。
  • @Progman,我试图在 cmets 中进行描述。希望能解开所有疑惑。没有其他与问题相关的代码。
  • @Progman,是的。非常感谢。不知道为什么我以前没有尝试过。

标签: java spring spring-boot junit mockito


【解决方案1】:

由于您使用的是@InjectMocks,因此您应该在类级别上使用@RunWith(MockitoJUnitRunner.class),一切都会正常工作。

如果你想使用@RunWith(SpringRunner.class) 那么使用@MockBean 和@SpyBean 来编写测试。

编辑:

你可以看到更多@RunWith(SpringRunner.class) vs @RunWith(MockitoJUnitRunner.class) here

另外,你可以查看这个Why we use Mockitojunitrunner class in our junit test?

@RunWith(SpringRunner.class) with Spring Boot

另外,请检查这个Mockito - difference between doReturn() and when()

【讨论】:

  • 它没有解决我的问题。已将其更改为使用 SpyBean 注释而不是 InjectMocks,但仍然出现 indexoutofbounds 异常。
  • 你能用新代码更新你的问题吗?或者在这里添加新代码
  • Progman 的评论回答了我的问题。事实证明,该线程非常有帮助。使用 doReturn 而不是 when thenReturn。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多