使用TestHazelcastInstance测试HazelcastClient

时间:2017-06-08 16:44:15

标签: java spring-boot integration-testing hazelcast spring-boot-test

有一个基于spring-boot的hazelcast微服务,通过HazelcastClient连接到hazelcast集群。

如果使用TestHazelcastInstance模拟集群,那么编写集成测试的过程是什么?

尝试创建一个提供@TestConfiguration的{​​{1}}配置类,但在这种情况下,另一个配置类TestHazelcastInstance(提供客户端)似乎没有执行,结果在客户端实例中没有实例化。

有什么见解?

App.java

HazelcastConfig

HazelcastConfig.java (提供客户端):

@SpringBootApplication
public class App {

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

AppTest.java ,有问题的测试:

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

    private ClientConfig config;

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

TestConfig.java ,提供@RunWith( SpringRunner.class ) @SpringBootTest( classes = { TestConfig.class } ) @ActiveProfiles( "test" ) public class AppTest { @Test public void contextLoads() { } }

TestHazelcastInstance

2 个答案:

答案 0 :(得分:1)

以下是使用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();
  }
}

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

干杯

维克

答案 1 :(得分:0)

鉴于它是集成测试,您可能希望使用Hazelcast的嵌入式实例进行测试: <div class="parent"> <div class="child"> (copy your content here) </div> </div>