使用自动装配的 Spring bean 的 JUnit?
代码如下:
public class Customer
{
@Autowired
private Person person;
//some business logic using person object
}
现在我需要为 Customer 类编写 jUnit 测试用例,该怎么做? 我是否应该使用 Mockito 来模拟 person 对象,然后执行业务逻辑,如果是,如何将模拟的 person 对象设置为 Customer 的属性,而不需要任何 setter/getter?
谢谢!
Here is the code:
public class Customer
{
@Autowired
private Person person;
//some business logic using person object
}
Now I need to write the jUnit test case for the Customer class, how to go about it?
Shall i use Mockito to mock the person object and then execute the business logic and if yes the how to set the mocked person object as the property of the Customer without any setter/getter?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来你想太多了。
我不会嘲笑业务对象模型;当您不需要集成测试时,这适用于基于接口的类。
我不会将
Person
注入到 JUnit 测试中;我只需调用“new
”,实例化适合我的测试的内容,然后继续进行。如果您的客户必须拥有 Person 的实例,我建议使用构造函数注入。如果必须的话,你可以通过这种方式传递一个模拟 Person。
Sounds to me like you're overthinking it.
I would not mock a business object model; that's for interface-based classes when you don't want an integration test.
I would not inject a
Person
into a JUnit test; I'd simply call "new
", instantiate what was appropriate for my test, and get on with it.If your Customer has to have an instance of Person, I'd recommend constructor injection. You can pass a mock Person that way if you must.