模拟 属性 值驻留在构造函数中并在使用 @injectBean 注释时添加该模拟

Mock Property value resides in constructor and add that mock while using @injectBean annotation

我有一个 class,其中一个属性从外部回购中获取价值。

public class Demo() {
   private final Repository repository;
   private final long attr;

   public Demo(Repository repository) {
     this.repository = repository;
     this.attr = this.getValue();
   }
  
   private Long getValue() {
     return repository.getValue();
   }
   ... Rest of the code
}

现在我想为它写一个单元测试。

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class DemoTest() {
  @Mock
  private Repository repository;

  @InjectMocks
  private Demo demo;

  @BeforeEach
  void setUp() {
    registrationUtil = new RegistrationUtil();
    MockitoAnnotations.initMocks(this);

}

当我 运行 这个片段时,它在 repository.getValue() 中显示 空指针异常 我可以知道如何正确模拟该值以避免异常吗?

InjectMocks 不工作的原因可能是因为您的 Repository 字段是 Final。

请参考:Mockito injection not working for constructor AND setter mocks together

分辨率:

示例演示 Class:

注意它不是 Spring Class,只是一个简单的 pojo) 只是为了展示我们在这里没有自动装配任何东西。

import com.example.mongodb.embedded.demo.repository.UserRepository;

public class Demo {

    private final UserRepository repository;

    public Demo(UserRepository repository) {
        this.repository = repository;
    }

    private Long getValue() {
        return repository.count();
    }

    public String toString(){
        return "Count: " + getValue();
    }
}

package com.example.demo;

import com.example.mongodb.embedded.demo.repository.UserRepository;
import com.example.mongodb.embedded.demo.service.Demo;

import org.junit.Rule;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
class DemoApplicationTest {

    @Mock
    private UserRepository userRepository;

    private Demo noneAutoWiredDemoInstance;

    @Test
    public void testConstructorCreation() {

        MockitoAnnotations.initMocks(this);
        Mockito.when(userRepository.count()).thenReturn(0L);

        noneAutoWiredDemoInstance = new Demo(userRepository);

        Assertions.assertEquals("Count: 0", noneAutoWiredDemoInstance.toString());
    }
}