单元测试避免在 A 类测试方法中调用 B 类构造函数 [英] unit test avoid class B constructor call in class A test method

查看:55
本文介绍了单元测试避免在 A 类测试方法中调用 B 类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ClassA 和 ClassB,我在 Class B 构造函数中实例化了一些检测依赖项,所以我想避免在测试 Class A 的 foo 方法时调用 Class B 构造函数.A 类的 foo 方法创建了 B 类的一个实例.我正在使用 mockito 有没有办法告诉测试用例,当调用 TestClassA.foo() 方法时,不要实例化 ClassB,而是返回虚拟的 ClassB.

解决方案

我通过将 B 类实例化责任委托给 Factory 类来解决我的这个问题.然后在测试时使用mockito模拟工厂类并调用makeClassB()方法获取ClassB的实例,同时使用Mockito.when(factoryMock.makeClassB(anyParameters)).thenReturn(MockClassB)>

现在在 TestClassA 中,我可以调用 ClassA 的 foo() 方法,该方法现在使用 Factory 类来创建 ClassB 的实例,而不是直接创建 ClassB 实例.

查看这篇文章https://stackoverflow.com/a/21262999/3805770.

I have ClassA and ClassB, i have some instrumentation dependencies instantiated in Class B constructor so i want to avoid Class B constructor being called when testing Class A's foo method. Class A's foo method creates an instance of class B. I am using mockito is there any way to tell test case that when TestClassA.foo() method is called don't instantiate ClassB but return dummy ClassB.

解决方案

I solved this problem of mine by delegating the Class B instantiating responsibility to a Factory class. Then while testing used mockito to mock the factory class and called the makeClassB() method to get instance of ClassB, also used Mockito.when(factoryMock.makeClassB(anyParameters)).thenReturn(MockClassB)

And now in TestClassA i can call ClassA's foo() method which now uses Factory class to create instance of ClassB instead of directly creating ClassB instance.

check this post https://stackoverflow.com/a/21262999/3805770.

这篇关于单元测试避免在 A 类测试方法中调用 B 类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆