如何单元测试构造函数弹簧启动调用的方法
我想知道如何在以下代码中单位测试寄存器()方法单元,
@Component
@Slf4j
public class Abc {
private Xyz xyz;
@Autowired
public Abc(Xyz xyz) {
this.xyz = xyz;
try {
register();
} catch (Exception e) {
log.warn("Unsupported");
}
}
private void doSomething(String ts) {
//do Something
}
private void register() {
//register something
}
}
如何在Spring Boot应用程序中对此方法进行单元测试。当我尝试一些单元测试时,构造函数甚至在测试方法执行之前就被调用
I would like to know how to unit test register() method in the below code
@Component
@Slf4j
public class Abc {
private Xyz xyz;
@Autowired
public Abc(Xyz xyz) {
this.xyz = xyz;
try {
register();
} catch (Exception e) {
log.warn("Unsupported");
}
}
private void doSomething(String ts) {
//do Something
}
private void register() {
//register something
}
}
How can I unit test this method in a spring boot application. When I try some unit tests the constructor is called even before test method execution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能通过检查使用ABC类创建的对象的状态来测试吗?
这是检查私人方法的调用,因此,只要行为和外部状态相同,就可以重构类的内部工作,而无需更改测试。
如果您发现自己想检查是否在单元测试中调用了私人方法,那么这是一种气味,我认为应该重新考虑您的方法。其他一些问题已经涵盖了类似领域。
如果这些方法与某些外部组件进行交互,则可以像平常一样使用任何方法模拟这些组件,然后验证交互作用如您所期望的。这种互动是否以一种或另一种方式发生,应该是ABC类的实现细节,在外部,您不应该在乎。
Can you not test by checking the state of your object created with class Abc ?
This is preferable to checking the calling of private methods as then you can refactor the inner working of the class without having to change the tests, as long as the behaviour and external state is the same.
If you find yourself wanting to check that private methods have been called in a unit test then this is a smell and should rethink your approach I think. Some other questions have already covered similar areas.
If these methods are interacting with some external components then you can mock these components as you normally would with any method and then validate the interaction is as you expect. Whether that interaction happens in one method or another internally should be an implementation detail of the Abc class and externally you shouldn't care.