如何使用Mockito从自定义属性文件加载junit测试的值?

如何使用Mockito从自定义属性文件加载junit测试的值?,junit,mockito,Junit,Mockito,我编写这个测试类是为了检查服务。这在test/java/example/devp/test.java文件夹中 @RunWith(MockitoJUnitRunner.class) @TestPropertySource("classpath:conn.properties") public class DisplayServiceTest { @Value("${id}") private String value; @Mock private DisplayRepository D

我编写这个测试类是为了检查服务。这在test/java/example/devp/test.java文件夹中

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource("classpath:conn.properties")

public class DisplayServiceTest {


@Value("${id}")
private String value; 


@Mock
private DisplayRepository DisplayReps;

@InjectMocks
private DisplayService DisplayService;

@Test
public void whenFindAll_thenReturnProductList() {

Menu m = new Menu()
m.setId(value); //when I print value its showing 0

List<Display> expectedDisplay = Arrays.asList(m);
doReturn(expectedDisplay).when(DisplayReps).findAll();
List<Display> actualDisplay = DisplayService.findAll();
assertThat(actualDisplay).isEqualTo(expectedDisplay);
}

从自定义属性文件设置属性的正确方法是什么?导致其未加载值?

@TestPropertySource
是spring注释,因此需要使用
SpringRunner

您可以使用
MockitoAnnotations.initMocks(this)初始化Mockito,检查下面的示例

@RunWith(SpringRunner.class)
@TestPropertySource(“类路径:conn.properties”)
公共类DisplayServiceTest{
@值(“${id}”)
私有字符串值;
// ...
@以前
公共作废设置(){
initMocks(this);
}
// ...
}

Mockito是一个mocking框架,所以通常不能用Mockito加载属性文件

现在您已经使用了
@TestPropertySource
,这是Spring测试的一部分,它确实允许加载属性文件(但与mockito无关)。但是,使用它需要与
SpringRunner
一起运行,通常它适合集成测试,而不是单元测试(SpringRunner主要加载Spring的应用程序上下文)

所以,如果您不想在这里使用spring,您应该“手动”使用它。从类路径加载属性文件有许多不同的方法(例如使用
getClass().getResourceAsStream()
获取指向资源文件的输入流,并使用
Properties\load(InputStream)
将其读入属性)

您还可以使用其他第三方(而不是mockito),比如apachecommons io,通过
IOUtils
类读取流


如果您想与JUnit 4.x集成,您甚至可以创建一个规则,如所述,您可以只使用Mockito和JUnit 4。在
@Before
方法中,调用
MockitoAnnotations.initMocks
并加载属性文件:

public class DisplayServiceTest {

    private String value;

    @Mock
    private DisplayRepository displayReps;

    @InjectMocks
    private DisplayService displayService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        Properties prop = loadPropertiesFromFile("conn.properties");
        this.value = prop.getProperty("id");
    }

    private Properties loadPropertiesFromFile(String fileName) {
        Properties prop = new Properties();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream stream = loader.getResourceAsStream(fileName);
            prop.load(stream);
            stream.close();
        } catch (Exception e) {
            String msg = String.format("Failed to load file '%s' - %s - %s", fileName, e.getClass().getName(),
                    e.getMessage());
            Assert.fail(msg);
        }
        return prop;
    }

    @Test
    public void whenFindAll_thenReturnProductList() {

        System.out.println("value: " + this.value);

        Menu m = new Menu();
        m.setId(this.value); // when I print value its showing 0

        List<Display> expectedDisplay = Arrays.asList(m);

        Mockito.doReturn(expectedDisplay).when(this.displayReps).findAll();

        List<Display> actualDisplay = this.displayService.findAll();

        Assert.assertEquals(expectedDisplay, actualDisplay);
    }

}
公共类DisplayServiceTest{
私有字符串值;
@嘲弄
私有displayReps存储库displayReps;
@注射模拟
专用显示服务显示服务;
@以前
公共作废设置(){
initMocks(this);
Properties prop=loadPropertiesFromFile(“conn.Properties”);
this.value=prop.getProperty(“id”);
}
私有属性loadPropertiesFromFile(字符串文件名){
Properties prop=新属性();
试一试{
ClassLoader=Thread.currentThread().getContextClassLoader();
InputStream=loader.getResourceAsStream(文件名);
道具载荷(流);
stream.close();
}捕获(例外e){
String msg=String.format(“加载文件'%s'-%s-%s'失败”,文件名为e.getClass().getName(),
e、 getMessage());
Assert.fail(msg);
}
返回道具;
}
@试验
当findell\u thenReturnProductList()时公共无效{
System.out.println(“值:“+this.value”);
菜单m=新菜单();
m、 setId(this.value);//当我打印值时,它显示为0
List expectedDisplay=Arrays.asList(m);
Mockito.doReturn(expectedDisplay).when(this.displayReps.findAll();
List actualDisplay=this.displayService.findAll();
Assert.assertEquals(预期显示、实际显示);
}
}
public class DisplayServiceTest {

    private String value;

    @Mock
    private DisplayRepository displayReps;

    @InjectMocks
    private DisplayService displayService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        Properties prop = loadPropertiesFromFile("conn.properties");
        this.value = prop.getProperty("id");
    }

    private Properties loadPropertiesFromFile(String fileName) {
        Properties prop = new Properties();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream stream = loader.getResourceAsStream(fileName);
            prop.load(stream);
            stream.close();
        } catch (Exception e) {
            String msg = String.format("Failed to load file '%s' - %s - %s", fileName, e.getClass().getName(),
                    e.getMessage());
            Assert.fail(msg);
        }
        return prop;
    }

    @Test
    public void whenFindAll_thenReturnProductList() {

        System.out.println("value: " + this.value);

        Menu m = new Menu();
        m.setId(this.value); // when I print value its showing 0

        List<Display> expectedDisplay = Arrays.asList(m);

        Mockito.doReturn(expectedDisplay).when(this.displayReps).findAll();

        List<Display> actualDisplay = this.displayService.findAll();

        Assert.assertEquals(expectedDisplay, actualDisplay);
    }

}