在JUnit5中导入特定的Bean,而不加载整个应用程序。

huangapple go评论93阅读模式
英文:

Import a specific bean in JUnit5 without load all application

问题

我在我的项目中有一个配置类:

@Configuration
public class MyConfiguration {

    //客户端SDK配置构建
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

}

现在我想在我的单元测试类中使用这个bean,而不加载整个应用程序上下文:

@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes = {MyConfiguration.class})
public class Test {

    @Autowired
    private MyBean mybean;

    @Test
    public void methodTest() {
        //使用mybean类的方法
        mybean.method();
    }

}

但是当运行测试时(在我调用mybean定义的地方),我得到了一个 NullPointerException 错误。

可能出了什么问题?

谢谢。

英文:

I have a configuration class on my project

@Configuration
public class MyConfiguration {

    //client SDK configuration build
    @Bean
    public MyBean myBean() {
		return new MyBean();
	}
	
}

Now I want to use this bean on my unit test class without load all application context

@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes = {MyConfiguration.class})
public class Test {

    @Autowired
    private MyBean mybean;

    @Test
    public void methodTest() {
        //use mybean class methods
        mybean.method();
    }

}

But I am getting an NullPointerException error when run the test (in the line where I invoke mybean definition)

What could be wrong ?

Thanks

答案1

得分: 0

将以下内容进行翻译:

@ExtendWith(MockitoExtension.class)

替换为

@ExtendWith(SpringExtension.class)

SpringExtension 允许在 JUnit5 中使用 Spring。一旦你使用了它,JUnit 将调用该扩展,该扩展将读取 Spring 注解。

英文:

Replace

@ExtendWith(MockitoExtension.class)

with

@ExtendWith(SpringExtension.class)

SpringExtension enables the use of Spring with JUnit5. Once you have that, JUnit will call the extension, which in turn will read the Spring annotations.

huangapple
  • 本文由 发表于 2023年8月4日 00:35:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定