英文:
Unit testing with inject annotation
问题
以下是翻译好的内容:
如何对使用 @inject
注解的类进行单元测试:类 A{
@inject
private B b;
void foo(){
b.funcInClassB();
}
我对单元测试还不太熟悉,因为在调用 b.funcInClassB()
时会抛出空指针异常,因为 b 为空。我编写了以下测试:
class Atest{
@MockBean
private B b;
@Test
void foo(){
when(b.funcInClassB()).willReturn("something");
A a = new A();
a.foo();
}
}
英文:
How do I unit test a class that uses @inject
annotation:class A{
@inject
private B b;
void foo(){
b.funcInClassB();
}
I am new to unit testing and having troubles testing this function because when calling b.funcInClassB()
it throws NullPointerException because b is null.
I wrote the following test:
class Atest{
@MockBean
private B b;
@Test
void foo(){
when(b.funcInClassB()).willReturn("something");
A a = new A();
a.foo();
}
}
答案1
得分: 0
我找到解决方法:
class Atest{
@MockBean
private B b;
@Autowired
A a;
@Test
void foo(){
when(b.funcInClassB()).willReturn("something");
// A a = new A();
a.foo();
}
}
英文:
I figured it out:
class Atest{
@MockBean
private B b;
@Autowired
A a;
@Test
void foo(){
when(b.funcInClassB()).willReturn("something");
// A a = new A();
a.foo();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论