Junit / Fongo: как использовать Fongo в модульном тесте для проверки NotNull - PullRequest
0 голосов
/ 06 ноября 2018

Я пишу базовый модульный тест, который проверяет, является ли возвращаемый запрос (тип DataVersion) не нулевым. Я должен убедиться, что я использую Fongo для тестирования моей базы данных.

Это класс репо:

    @Repository
    public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {

    @Autowired
    MongoOperations mongoOperations;

    public DataVersionDaoMongo() {
        initType();
    }

    @Override
    public DataVersion findByDBAndCollection(String dbName, String collectionName) {

        Criteria criteria = Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName);
        Query query = Query.query(criteria);
        return mongoOperations.findOne(query, DataVersion.class);

    }
}

Это мой юнит-тест:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
    @Autowired
    private DataVersionDaoMongo dataVersionDaoMongo;
    @Autowired
    private MongoOperations mongoOperations;
    private DataVersion dataVersion;

    @Rule
    public FongoRule fongoRule = new FongoRule();

    @Test
    public void findByDBAndCollection() {
       //String dbname = "mydb";
       //String collectionName = "mycollection";
       // DB db = fongoRule.getDB(dbname);
       //DBCollection collection = db.getCollection(collectionName);
       //Mongo mongo = fongoRule.getMongo();
       //collection.insert(new BasicDBObject("name", "randomName"));

       DataVersion dataVersion = new DataVersion();
       dataVersion.setDbName("DBDataVersion");
       dataVersion.setVersion("version1");
       dataVersion.setCollectionName("DataVersion");
       mongoOperations.insert(dataVersion);**strong text**  
       assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
    }
}

Вот класс DataVersion:

@Document(collection = "DataVersion")
public class DataVersion {

    @Id
    private String id;
    private String dbName;
    private String collectionName;
    private String version;
    private boolean isCompleted;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getDbName() {
        return dbName;
    }
    public void setDbName(String dbName) {
        this.dbName = dbName;
    }
    public String getCollectionName() {
        return collectionName;
    }
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public boolean isCompleted() {
        return isCompleted;
    }
    public void setCompleted(boolean isCompleted) {
        this.isCompleted = isCompleted;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((collectionName == null) ? 0 : collectionName.hashCode());
        result = prime * result + ((dbName == null) ? 0 : dbName.hashCode());
        result = prime * result + (isCompleted ? 1231 : 1237);
        result = prime * result + ((version == null) ? 0 : version.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DataVersion other = (DataVersion) obj;
        if (collectionName == null) {
            if (other.collectionName != null)
                return false;
        } else if (!collectionName.equals(other.collectionName))
            return false;
        if (dbName == null) {
            if (other.dbName != null)
                return false;
        } else if (!dbName.equals(other.dbName))
            return false;
        if (isCompleted != other.isCompleted)
            return false;
        if (version == null) {
            if (other.version != null)
                return false;
        } else if (!version.equals(other.version))
            return false;
        return true;
    }
}

Это файл testApplicationContext:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">


    <bean name="fongo" class="com.github.fakemongo.Fongo">
        <constructor-arg value="InMemoryMongo" />
    </bean>
    <bean id="mongo" factory-bean="fongo" factory-method="getMongo" />

    <mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />

    <!-- localhost settings for mongo -->
    <!--<mongo:db-factory id="mongoDbFactory" />-->

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory"/>
    </bean>

</beans>

Хотя мой модульный тест проходит, потому что я объявил переменную dataVersion и установил значения, такие как DbName, Version, CollectionName, внутри своего теста и вызвал метод findByDBandCollection. Но я не использую Fongo DB здесь, и я хочу использовать его. Как я могу использовать Fongo db в моем тесте и использовать assertThat, чтобы DataVersion, возвращаемый при вызове метода findByDBAndCollection, не был нулевым?

1 Ответ

0 голосов
/ 06 ноября 2018

Я создал пример , который иллюстрирует это.

...