How to test Mongodb by Spring MongoTemplate

here is the example:

1. model

package com.eifesun.monitor.web.model;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import com.eifesun.monitor.DeviceType;
import com.eifesun.monitor.inverter.power_20k.ErrorCode;

@Document(collection = "alarm_logs")
public class AlarmLogs implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    private long id;

    @Indexed
    private long alarmDate;

    private String deviceType;
    private String clientId;
    private String errorType;
    private int errorValue;
    private long startDate;
    private long cleanDate;

    @Transient
    private final String dateParten = "MM/dd/yyyy h:mm";
    @Transient
    private String name;

    public AlarmLogs() {
    }

    public AlarmLogs(DeviceType deviceType, String clientId, String errorType, int errorValue) {
        this.deviceType = deviceType.toValue();
        this.clientId = clientId;
        this.errorType = errorType;
        this.errorValue = errorValue;
        this.startDate = DateTime.now().getMillis();
        this.alarmDate = new LocalDate().toDateTimeAtStartOfDay().getMillis();
    }

    public String getStartDate() {
        return new DateTime(startDate).toString(dateParten);
    }

    public void setStartDate(long startDate) {
        this.startDate = startDate;
    }

    public boolean getAlarmIsCleaned() {
        return this.cleanDate != 0;
    }

    /**
     * get alarm remain period time (unit: minute)
     * 
     * @return
     */
    public long getAlarmRemainedTime() {
        if (getAlarmIsCleaned()) {
            return TimeUnit.MILLISECONDS.toMinutes(cleanDate - startDate);
        }
        else {
            return TimeUnit.MILLISECONDS.toMinutes(DateTime.now().getMillis() - startDate);
        }
    }

    public void setCleanDate(long cleanDate) {
        this.cleanDate = cleanDate;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setAlarmDate(DateTime alarmDate) {
        this.alarmDate = alarmDate.getMillis();
    }

    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }

    public String getErrorMessage() {
        return ErrorCode.getType(errorType).getDescription(errorValue);
    }

    public String getErrorType() {
        return errorType;
    }

    public int getErrorValue() {
        return errorValue;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

 

2.db Repository

package com.eifesun.monitor.web.repository;

import static org.springframework.data.domain.Sort.Direction.DESC;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.List;

import org.joda.time.DateTime;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import com.eifesun.monitor.web.model.AlarmLogs;

@Repository
public class AlarmLogsRepositoryImpl extends SequenceRepostory implements AlarmLogsRepository {

    public void setMongo(MongoTemplate mongo) {
        this.mongo = mongo;
    }

    @Override
    public List<AlarmLogs> findAlarmLogs(DateTime date, int lastId) {
        //@formatter:off
        final List<AlarmLogs> alarmlogs = mongo.find(
                                            query(where("startDate").gte(date.getMillis()).
                                                  and("_id").gt(lastId)).
                                                  with(new Sort(DESC, "_id")).
                                                  limit(100), AlarmLogs.class);
        //@formatter:on
        return alarmlogs;
    }

    @Override
    public void save(AlarmLogs logs) {
        logs.setId(getNextSequence("alarm_logs"));
        mongo.save(logs);
    }

}

 abstract repostroy for sequence fetch

@Repository
public abstract class SequenceRepostory {

    @Autowired
    protected MongoTemplate mongo;

    public abstract void setMongo(MongoTemplate mongo);

    public long getNextSequence(String collectionName) {

        final Counter counter =
                mongo.findAndModify(query(where("_id").is(collectionName)), new Update().inc("seq", 1), options().returnNew(true), Counter.class);
        return counter.getSeq();
    }
}

 

3. repostory unit test

package com.eifesun.mornitor.server;

import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import java.util.List;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.eifesun.monitor.web.command.AlarmQueryType;
import com.eifesun.monitor.web.model.AlarmLogs;
import com.eifesun.monitor.web.repository.AlarmLogsRepositoryImpl;
import com.foursquare.fongo.Fongo;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import com.mongodb.Mongo;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class AlarmLogsRepositoryTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private AlarmLogsRepositoryImpl alarmRepo;

    @Rule
    public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("mongodb-test");

    @Test
    @UsingDataSet(locations = {"testFindAlarmLogs.json"}, loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
    public void testFindAlarmLogs() {
        List<AlarmLogs> list = alarmRepo.findAlarmLogs(AlarmQueryType.AUTO.getAlarmDate(), 0);
        assertThat(list.size(), equalTo(4));
    }

    @Configuration
    @EnableMongoRepositories
    @ComponentScan(basePackageClasses = {AlarmLogsRepositoryImpl.class})
    @PropertySource("classpath:application.properties")
    static class RepositoryTestConfiguration extends AbstractMongoConfiguration {

        @Override
        protected String getDatabaseName() {
            return "mongodb-test";
        }

        @Override
        public Mongo mongo() {
            return new Fongo("mongo-test").getMongo();
        }

        @Override
        protected String getMappingBasePackage() {
            return "com.eifesun.monitor.web.model";
        }

    }
}

 

enjoy it.

你可能感兴趣的:(template)