1

有一个基于 spring-boot 的 hazelcast 微服务,它通过HazelcastClient.

考虑到集群是使用 ? 模拟的,编写集成测试的过程是TestHazelcastInstance什么?

尝试创建一个@TestConfiguration提供 的配置类TestHazelcastInstance,但在这种情况下,另一个配置类HazelcastConfig(提供客户端)似乎没有执行,导致客户端实例没有被实例化。

有什么见解吗?

应用程序.java

@SpringBootApplication
public class App {

    public static void main( final String[] args ) {
        SpringApplication.run( App.class, args );
    }
}

HazelcastConfig.java(提供客户端):

@Configuration
@ConfigurationProperties( prefix = "hazelcast" )
@Getter
@Setter
public class HazelcastConfig {

    private ClientConfig config;

    @Bean
    public HazelcastInstance hazelcastInstance() {
        return HazelcastClient.newHazelcastClient( config );
    }
}

AppTest.java,有问题的测试:

@RunWith( SpringRunner.class )
@SpringBootTest( classes = { TestConfig.class } )
@ActiveProfiles( "test" )
public class AppTest {

    @Test
    public void contextLoads() {
    }
}

TestConfig.java,提供TestHazelcastInstance

@TestConfiguration
@Profile( "test" )
@ConfigurationProperties( prefix = "hazelcast.server" )
public class TestConfig {

    private Config config;

    @Bean( "hazelcastInstance_TEST" )
    public HazelcastInstance hazelcastInstance() {
        return new TestHazelcastInstanceFactory( 1 ).newHazelcastInstance( config );
    }
}
4

2 回答 2

2

这是一个使用单元测试 hazelcast 代码的示例TestHazelcastFactory

public class NativeTestingHazelcast {

    private TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory();

  private HazelcastInstance member;
  private HazelcastInstance client;

 @Before
 public void setUp() throws Exception {
     member = hazelcastFactory.newHazelcastInstance();
     client = hazelcastFactory.newHazelcastClient();
 }

 @Test
 public void simpleTest() throws Exception {
     final IMap<Integer, String> testMapFromMember = member.getMap("testMap");
     testMapFromMember.set(1, "test1");

    final IMap<Integer, String> testMap = client.getMap("testMap");
    final String value = testMap.get(1);
    assertEquals("member puts, client gets", value, "test1");
}

@After
public void tearDown() throws Exception {
    hazelcastFactory.shutdownAll();
  }
}

如果您还有其他问题,请告诉我。

干杯

维克

于 2017-06-14T05:07:26.267 回答
1

鉴于它是一个集成测试,您可能希望使用 Hazelcast 的嵌入式实例进行测试: HazelcastInstance testInstance = Hazelcast.newHazelcastInstance(config);

于 2017-06-09T15:16:25.197 回答