我已经创建了一个简单的单元测试,但是IntelliJ错误地将它突出显示为红色。将其标记为错误

没有豆子?

如你所见,它通过了测试?所以它一定是自动连接的?


当前回答

您是否检查过在服务实现之上使用了@Service注释? 这对我很管用。

import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserServices {}

其他回答

我有这个问题。只使用

@SpringBootTest

@AutoConfigureMockMvc

带有测试类的注释。

检查bean的包是否正确编写

//Check if this is written right 
package com.package1.package2.package3


import ...

@Service
class ServiceX {

  ...

}

你所需要做的是让这个工作是以下代码:

@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}

看起来您试图在没有实际激活WebEnvironment的情况下运行测试。

解决方案非常简单,只需添加带有必需配置的@SpringBootTest注释。

这里有一个例子:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // Run the server for testing.
public class mockTest {

    @Autowired
    // Should work now
}

有时——就我而言——原因是一个错误的输入。我不小心导入了

import org.jvnet.hk2.annotations.Service

而不是

import org.springframework.stereotype.Service

盲目地接受Idea建议的导入中的第一个选择。第一次发生的时候我花了几分钟:-)