【问题标题】:How to send @Autowired field in @InjectMocks如何在@InjectMocks 中发送@Autowired 字段
【发布时间】:2021-02-25 09:49:05
【问题描述】:

我正在单元测试一个类 AuthController,它有这个构造函数

@Autowired
public AuthController(DynamicBeanFactory beanService) {
   Sysout(beanService); //here null is coming - Point-1
}

在测试课上,我做了:

@Mock
DynamicBeanFactory beanService;

@InjectMocks
AuthController authController(beanService);

- Below @Test are there -

现在当我运行这个时:

point-1 上面的构造函数中的 beanService 的值即将到来 null


另外,当我在 @InjectMocks 的地方做 @Autowired 时,它可以工作。

下面我分享了人们提出的一些问题。

问)什么是 AuthController?

A)它只是一个具有我上面共享的构造函数的类。

Q) 什么是动态 Bean 工厂?

A) 这是一个类似下面的服务类:

@Service
public class DynamicBeanFactory

   @Autowired
   public DynamicBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory)
   }
}

【问题讨论】:

  • 你需要使用@Mock而不是@Autowired,也不要把spring和mocking混为一谈。您不应该在单元测试中真正使用 spring
  • @Lino 仍然 null 正在进入构造函数。
  • 请提供完整的minimal reproducible example,目前您的代码无法编译。 AuthController authController(beanService) 是什么?
  • 我已经更新了问题,请检查。
  • 它仍然不是minimal reproducible example。你是如何运行你的测试的?你是如何初始化你的模拟的(你是在 @BeforeEach 中使用 MockitoAnnotations.init(this),还是在使用 @RunWith(MockitoJUnitRunner.class))?还有很多悬而未决的问题

标签: java unit-testing mocking mockito junit5


【解决方案1】:

如果您使用@Mock,请记住将@RunWith(MockitoJUnitRunner.class) 添加到您的测试类,否则它不会初始化模拟。

【讨论】:

  • 我只放了@SpringBootTest,我应该在其中包含@RunWith(MockitoJUnitRunner.class) 吗?
  • 如 cmets 中所述,您不应该使用 Spring 进行单元测试,您可以将其替换为 @RunWith
  • 我做了,还是给null
  • 去掉authController @InjectMocks AuthController authController;的参数
  • 现在 AuthController 本身在 @Test 方法中为空
【解决方案2】:

您可以将@MockBean 用于@Autowired 依赖项。 像这样:

@MockBean
DynamicBeanFactory beanService;

试试这个,它对我有用。我假设AuthController 有一个以DynamicBeanFactory 为参数的构造函数,并且没有其他依赖项。

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
class TestApplicationTests {
            
    @InjectMocks
    DynamicBeanFactory d;
    
    @MockBean 
    AuthController a;

    @Test
    public void test() {
        Assert.notNull(a);
    }
}

【讨论】:

  • 构造函数中仍然存在“null”。
  • 能否分享init()和setUp()的sn-p代码。
  • 我已经更新了这个问题。我的代码中没有 init() 和 setup()。请说明我是否需要放置它们。
  • @AshutoshTiwari,试试我上面提供的代码。
  • 好吧,Manjeet 在我尝试测试时尝试这个,我正在测试的类没有选择 application.properties。我是否需要使用一些注释或其他东西以便@Value 开始工作。仅供参考:如果我用 @Autowired 代替 @InjectMocks 就可以了
猜你喜欢
  • 2016-03-08
  • 2016-11-25
  • 2019-12-04
  • 1970-01-01
  • 2019-08-10
  • 2023-03-26
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多