@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作为非内部非静态类,但没有帮助。
以下是我在一个单独的课程中尝试的内容:
@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,赐教我。
Stacktrace:
显示java.lang.NullPointerException
在行号,我有声明:
environment.getProperty("bhavya",Boolean.class);
答案 0 :(得分:2)
尝试使用@RunWith(SpringJUnit4ClassRunner.class)
这是一个解释如何完成的示例 https://www.mkyong.com/unittest/junit-spring-integration-example/
以下是适用于问题中示例的代码示例:
package 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;
}
}
}
答案 1 :(得分:0)
尝试为您的测试课添加以下注释
@ContextConfiguration(classes = Config.class)
@SpringBootTest
@ExtendWith(SpringExtension.class)
@RunWith(SpringJUnit4ClassRunner.class)