如何测试一个方法,有一个无穷无尽的自动连接链?



这是我需要在mock中编写单元测试用例的(简化)方法,但是我得到一个空指针异常:

public class Class1 {
@Autowire
AutoWiredObject autoWiredObject;
public Object1 getAccount(boolean b1) {
Object1 object = new Object1();
autoWiredObject.setAllValues(object); //object.get("value") is set to something
//here. Also this is where the exception follows when I test the unit test method
return object;
}
}

我在测试类中尝试了这样的操作:

@InjectMocks 
Class1 myClass;
@Spy // I researched this is how we solve the issue of autowired
AutoWiredObject autoWiredObject = new AutoWiredObject();
@Test
public void testGetAccount() {
Object1 object = myClass.getAccount(true); //this is where the null pointer exception
//starts
assertTrue(object.get("value") != null);
}

对这种类型的方法进行单元测试的最佳方法是什么?顺便说一下,如果我检查AutowiredObject类的实现,setallvalues;方法在调用方法时也包含一个autowired对象,所以我的观点是,如何处理这个"链"autowired的? ?

或者有没有其他更简单的方法来测试

autowiredObject.setAllValues(object) 

? ?

如果你不能改变Class1的实现,我认为实例化间谍应该解决这个问题:

@Spy
AutoWiredObject autoWiredObject = new AutoWiredObject(/*parameters*/);

这里有一个关于模拟和间谍的很好的解释。

现在,如果你可以改变Class1

我个人倾向于编写和测试我的服务,而不管使用的是哪种注入框架。使用您的Class1作为一个例子,我将使用构造器注入器重写它:

public class Class1 {        
private final AutoWiredObject autoWiredObject;
@Autowire
public Class1(AutoWiredObject autoWiredObject) {
this.autoWiredObject = autoWiredObject;
} 
public Object1 getAccount(boolean b1) {
Object1 object = new Object1();
autoWiredObject.setAllValues(object);
return object;
}
}

现在我不需要@ injectmock或@Spy在测试期间,只是好的旧Mockito语法:

void testAccount() {
//arrange
AutoWiredObject autoWiredSpy = Mockito.spy(new AutoWiredObject(/*parameters*/));
Class1 myClass = new class1(autoWiredSpy);
//act
Object1 result = myClass.getAccount(true);
//assert
assertNotNull(result.get("value"));
} 

我假设AutoWiredObject有一个默认构造函数。也检查你的参数b1,因为你似乎没有使用它。

最新更新