@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@ActiveProfiles(profiles = "test")
@RunWith(MockitoJUnitRunner.class)
public class ConfigurationTest {
@Autowired
private Environment environment;
@Test
public void test1() throws Exception {
environment.getProperty("bhavya",Boolean.class);
}
@Configuration
@Profile("test")
@ComponentScan(basePackages={"com.bhavya.test"})
public static class EnvironmentServiceTestConfiguration{
@Bean
@Primary
public Environment environment(){
return Mockito.mock(Environment.class);
}
}
}
我还尝试将 EnvironmentServiceTestConfiguration 作为非内部非静态类,但没有帮助。
这是我在单独的类(class)中尝试的内容:
@RunWith(MockitoJUnitRunner.class)
@Profile("test")
@Configuration
class EnvironmentServiceTestConfiguration{
@Bean
@Primary
public Environment environment(){
return Mockito.mock(Environment.class)
}
}
也没用
测试类位于test/java/com.bhavya.test包中。 我正在尝试运行这个特定的测试 test1
这是我第一次进行此类测试。我以前从未使用过AnnotationConfigContextLoader.class,请赐教。
堆栈跟踪:
java.lang.NullPointerException
在我有声明的行号:
environment.getProperty("bhavya",Boolean.class);
最佳答案
尝试使用@RunWith(SpringJUnit4ClassRunner.class)
这是一个示例,解释如何做到这一点 https://www.mkyong.com/unittest/junit-spring-integration-example/
以下是适用于问题中示例的代码示例:
包com.example.demo.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class ConfigurationTest {
@Autowired
private Environment environment;
@Test
public void test1() throws Exception {
System.out.println(environment.getProperty("bhavya",Boolean.class));
}
@Configuration
@ComponentScan(basePackages={"com.example.demo.test"})
public static class EnvironmentServiceTestConfiguration{
@Bean
@Primary
public Environment environment(){
Environment env = Mockito.mock(Environment.class);
when(env.getProperty(eq("bhavya"), eq(Boolean.class))).thenReturn(true);
return env;
}
}
}
关于java - Spring Test无法获取Spring配置Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48089021/