如何模拟环境接口?

问题描述 投票:0回答:4

我正在尝试测试我的服务,如下所示:

import org.springframework.core.env.Environment;

@Service
public class MyService {
@Autowired Environment env;
...
...
}

如何模拟环境接口,或者如何创建环境接口?

spring mocking spring-test
4个回答
29
投票

Spring 提供了属性源和环境的模拟。这两个都可以在

org.springframework.mock.env
模块的
spring-test
包中找到。

这些内容在测试章节的模拟对象部分的参考手册中进行了简要记录。


6
投票

使用 Mockito,您应该能够像下面的代码一样做到这一点。请注意,您需要提供访问器,以便可以在运行时设置环境字段。或者,如果您只有几个自动装配字段,那么定义一个可以注入环境的构造函数会更干净。

import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

public class MyServicetest {

    // Define the Environment as a Mockito mock object
    @Mock Environment env;

    MyService myService;

    @Before
    public void init() {
        // Boilerplate for initialising mocks 
        initMocks();

        // Define how your mock object should behave
        when(this.env.getProperty("MyProp")).thenReturn("MyValue");

        // Initialise your service
        myService = new MyServiceImpl();

        // Ensure that your service uses your mock environment
        myService.setEnvironment(this.env);
    }

    @Test
    public void shouldDoSomething() {
        // your test
    }

}

3
投票

实现类有@Autowired环境env;因此,当您运行 >JUnit 测试用例时,您的实现类应该具有如下所示的构造函数:

public class SampleImpl{
@Autowired
Environment env
public SampleImpl(Environment envObj){
this.env = envObj}
}

您的 Junit 测试类应如下所示:

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.core.env.Environment;
import static org.mockito.Mockito.when;
public class SampleTest {   

     @Mock Environment env;

     @Before
      public void init(){
          env = mock(Environment.class);     
          when(env.getProperty("file.location"))
            .thenReturn("C:\\file\\");        
      }

          @Test
          public void testCall()throws Exception{
              SampleImpl obj = new SampleImpl(env);
              obj.yourBusinessMethods();

          }
}

希望这有帮助。谢谢史蒂夫。


1
投票

在基于 Spring 的测试中,您可以使用:

@ActiveProfiles
,因此激活一些配置文件(但这不是模拟)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test.xml")
@ActiveProfiles("myProfile")
public class ProfileTest {

  @Autowired
  MyService myService

  @Test
  public void demo() {
      assertTrue(myService.env.acceptsProfiles("myProfile"));
  }
}

但是我需要一个模拟,然后编写自己的模拟或使用模拟框架(Mokito 或 JMock)。

Environment
有一个子类
AbstractEnvironment
,你只需要重写
customizePropertySources(MutablePropertySources propertySources)
方法

@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
            Properties properties = ....
    propertySources.addLast(new MockPropertySource(properties));
}
© www.soinside.com 2019 - 2024. All rights reserved.