【问题标题】:How to mock lazy initialized Bean using Junit Mockito如何使用 Junit Mockito 模拟延迟初始化的 Bean
【发布时间】:2019-08-06 15:33:32
【问题描述】:

我有一个类,我在构造函数中使用延迟初始化自动装配它。但是我无法使用@Mock 来模拟它。它在我的测试类中引发空指针异常。

@Transactional
@Repository
public class A{
 private  B b;


  @Autowired
  public A(@Lazy B b {
      this.b= b;
  }
}  

Iam unable to mock the bean B.My test class is as follows.

@RunWith(MockitoJUnitRunner.class)
public class ATest{

  @Rule
  public ExpectedException thrown = ExpectedException.none();



  @InjectMocks
  A a;
  @Mock
  B b;
  Mockito.when(b.methodCall()).thenReturn("test");
}

上面的代码返回空指针异常,因为我无法模拟 B 类。请告诉我如何模拟这个。

【问题讨论】:

  • 请添加堆栈跟踪。还要添加class B(以及缺少的测试方法)。

标签: spring-boot junit mockito


【解决方案1】:

您正在使用带有@Autowired@Lazy 注释的构造函数注入应该在方法上方的位置。请尝试:

A 类:

@Transactional
@Repository
public class A {

    private B b;

    @Autowired
    @Lazy
    public A(B b) {
        this.b = b;
    }
}

B 类:

@Component
public class B {

    public String methodCall() {
        return "foo";
    }
}

测试类:

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

    @InjectMocks
    private A a;

    @Mock
    private B b;

    @Before
    public void before() {
        Mockito.when(b.methodCall()).thenReturn("test");
    }

    @Test
    public void myTest() {
        assertEquals(b.methodCall(), "test");
    }
}

【讨论】:

    【解决方案2】:

    我很确定这不是最好的解决方案,但我使用反射解决了它

        @Before
        public void before() {
            ReflectionUtils.setField(ReflectionUtils.findRequiredField(A.class, "b"), a, b);
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2019-11-08
      • 1970-01-01
      • 2013-03-07
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      相关资源
      最近更新 更多