单元测试与@Inject注解

huangapple go评论74阅读模式
英文:

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();
   }
}

huangapple
  • 本文由 发表于 2020年9月8日 04:05:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63783609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定