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

没有豆子?

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


当前回答

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

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

这里有一个例子:

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

    @Autowired
    // Should work now
}

其他回答

有时需要指明@ComponentScan应该在哪里扫描组件。你可以通过将包作为这个注释的参数来实现,例如:

@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})

然而,正如前面提到的,@SpringBootApplication注释替换了@ComponentScan,因此在这种情况下,你必须做同样的事情:

@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})

至少在我的案例中,Intellij停止了抱怨。

简单,你只需要做2步

添加休眠内核依赖项 将@Autowired改为@Resource。

==>> change @Autowired to  @Resource

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

import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserServices {}

在类级别使用@EnableAutoConfiguration注释和@Component。它将解决这个问题。

例如:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}

在存储库类上添加Spring注释@Repository。

我知道没有这个注释它也能工作。但是如果添加了这个,IntelliJ将不会显示错误。

@Repository
public interface YourRepository ...
...

如果您将Spring Data与扩展Repository类一起使用,则会产生冲突包。那么你必须直接标明包裹。

import org.springframework.data.repository.Repository;
...

@org.springframework.stereotype.Repository
public interface YourRepository extends Repository<YourClass, Long> {
    ...
}

接下来,您可以自动连接存储库而不会出现错误。

@Autowired
YourRepository yourRepository;

这可能不是一个好的解决方案(我猜您试图注册存储库两次)。但是为我工作,不要出错。

也许在IntelliJ的新版本中可以修复:https://youtrack.jetbrains.com/issue/IDEA-137023