Kaigo
Kaigo

Reputation: 1569

Redis unit test using redis mock

I'm using the following tool to run an embedded redis for unit testing.

In the beginning of my registrationService is creating a new instance of redis server.

@Import({RedisConfiguration.class})
@Service
public class RegistrationService

RedisTemplate redisTemplate = new RedisTemplate();  //<- new instance

public String SubmitApplicationOverview(String OverviewRequest) throws IOException {

    . . .

    HashMap<String,Object> applicationData = mapper.readValue(OverviewRequest,new TypeReference<Map<String,Object>>(){});

    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

    UUID Key = UUID.randomUUID();

    redisTemplate.opsForHash().putAll(Key.toString(), (applicationData)); //<-- ERRORS HERE

    System.out.println("Application saved:" + OverviewRequest);

    return Key.toString();
 }
}

And I'm starting a mock redis server in my Test below.

...

RedisServer redisServer;

@Autowired
RegistrationService RegistrationService;

@Before
public void Setup() {
    redisServer = RedisServer.newRedisServer();
    redisServer.start();
}

@Test
public void testSubmitApplicationOverview() {
    String body = "{\n" +
            "    \"VehicleCategory\": \"CAR\",\n" +
            "    \"EmailAddress\": \"[email protected]\"\n" +
            "}";
    String result = RegistrationService.SubmitApplicationOverview(body);

    Assert.assertEquals("something", result);
}

Redis settings in application.properties

#Redis Settings
spring.redis.cluster.nodes=slave0:6379,slave1:6379
spring.redis.url= redis://jx-staging-redis-ha-master-svc.jx-staging:6379
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=10.40.2.126:26379,10.40.1.65:26379
spring.redis.database=2

However, I'm getting a java.lang.NullPointerException error on the following line in my service under test (registrationService).

redisTemplate.opsForHash().putAll(Key.toString(), (applicationData));

Upvotes: 4

Views: 20754

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

According to the [redis-mock][1] documentation, creating an instance like this:

RedisServer.newRedisServer();  // bind to a random port

Will bind the instance to a random port. It looks like your code expects a specific port. I believe that you need to specify a port when you create the server by passing a port number like this:

RedisServer.newRedisServer(8000);  // bind to a specific port

Upvotes: 1

Related Questions