gpt4 book ai didi

java - 如何对始终 Autowiring 的接口(interface)进行单元测试 (Java)

转载 作者:行者123 更新时间:2023-11-30 09:32:57 29 4
gpt4 key购买 nike

所以我有一个接口(interface),我们称它为 X

所以在常规代码中我有:

public class doStuff()
{
@Autowired
private X x;

public stuff()
{
x.doYourThing();
}
}

虽然我不知道如何测试它。

如果我尝试:

public class XTest()
{
@Autowired
private X x;
public void test(){
string val = x.FillUpVal();
assertTrue("It didn't work",val=="hi");
}

}

我将 x 设置为 null,因此它会立即抛出 NullPointerException 并导致测试失败。我正在寻找一些关于正确方法的指导。

最佳答案

您实际上可以@Autowire 模拟对象。我推荐 Mockito 框架。更多信息和示例:http://code.google.com/p/mockito/

Injecting Mockito mocks into a Spring bean

更多关于模拟:

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

http://en.wikipedia.org/wiki/Mock_object

关于java - 如何对始终 Autowiring 的接口(interface)进行单元测试 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413640/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com