首页 > 解决方案 > 使用 Mockito 测试 Spring 环境配置文件

问题描述

Spring Framework 的最新版本已弃用 Environment.acceptsProfiles(String ...)以支持Environment.acceptsProfiles(Profiles ...)

在我的一个应用程序中更新它使测试变得更加困难,这里有一些测试代码来演示这个问题:

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.core.env.StandardEnvironment;

public class EnvironmentProfilesTest {

    @Test
    public void testItWithRealEnvironment() {
        System.setProperty(StandardEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "adrian");
        Environment environment = new org.springframework.core.env.StandardEnvironment();

        ToBeTested toBeTested = new ToBeTested(environment);
        assertTrue(toBeTested.hello("adrian"));
    }

    @Test
    public void testItWithMocklEnvironment() {
        Environment environment = mock(Environment.class);
when(environment.acceptsProfiles(Profiles.of("adrian"))).thenReturn(true);

        ToBeTested toBeTested = new ToBeTested(environment);
        assertTrue(toBeTested.hello("adrian"));
    }

    private static class ToBeTested {
        private Environment env;
        public ToBeTested(Environment env) {
            this.env = env;
        }

        public boolean hello(String s) {
            return env.acceptsProfiles(Profiles.of(s));
        }
    }
}

旧版本使用字符串参数来接受Profiles 很容易模拟。我究竟做错了什么?感觉 Profiles 类可能会使 equals() 方法受益?

标签: javaspringjunitmockito

解决方案


这不是春天,它只是不正确的方法。正如我所看到的,问题出在这部分代码中: when(environment.acceptsProfiles(Profiles.of("adrian"))).thenReturn(true);

您使用 mockEnvironment并尝试捕获Profiles类的实例,例如: .acceptsProfiles(eq(Profiles.of("adrian")))。您无法捕获它,因为您在方法中创建了另一个实例boolean hello(String s)并且Environment永远不会返回 true。

您刚刚描述了模拟的不正确行为,Environment您可以修复它:

any

@Test
    public void testItWithMocklEnvironment() {
        Environment environment = mock(Environment.class);
        when(environment.acceptsProfiles(any(Profiles.class))).thenReturn(true);

        ToBeTested toBeTested = new ToBeTested(environment);
        assertTrue(toBeTested.hello("adrian"));
    }

不使用模拟(我认为这就是你要找的):

@Test
    public void testItWithMocklEnvironment() {
        Environment environment = new org.springframework.core.env.StandardEnvironment();
        ((StandardEnvironment) environment).setActiveProfiles("adrian");

        ToBeTested toBeTested = new ToBeTested(environment);
        assertTrue(toBeTested.hello("adrian"));
    }

推荐阅读