lundi 23 novembre 2015

Not able to create mock class/object to replace the functionality of a private member object in my class for unit testing in gtest

I have a following class

#include "B.h"
class A{
    public:
        A();
        void Store(char* buff, int32_t len){
            if (!b_read){
                b_write = new B
            }
            b_write->write(buff, len);
        }
        void Read(char* buff, int32_t& len){
            if (!b_read){
                b_read = new B;
            }
            b_read->read(buff, len);
        }

    private:
        B *b_write;
        B *b_read;
}

B internally writes into a file (batch mode) and reads from that file(one record at a time). It does it in a time based format, i.e. say after every x secs.

I want to write a unit test case for class A and I think best way it to create a mock class for B(as I don't want it dependent on B and do time based operations) and where I don't have to create a file.

In my test I'll be storing store the data into a buffer and read from that buffer. However, I'm not sure how I can let my main class use and create object of my mock class B instead of original definition of B

This is what I've done

//Original class
class A{
    public:
        A();
        // I've created another constructor for this class.
        A(B *ptr){
            b_write = ptr;
            b_read = ptr;
        };
        void Store(char* buff, int32_t len){
            if (!b_read){
                b_write = new B
            }
            b_write->write(buff, len);
        }
        void Read(char* buff, int32_t& len){
            if (!b_read){
                b_read = new B;
            }
            b_read->read(buff, len);
        }

    private:
        B *b_write;
        B *b_read;
}
//New mock class B
class B{
    public:
        B(){
            m_buff = new char[1024];
            m_len = m_read = 0;
        }
        void write(char* buff, int32_t len){
            if (m_len + len >= 1024){
                return 0;
            }
            memcpy(buff + m_len, buff, len);
        }
        void read(char* buff, int32_t& len){
            if (!buff){
                buff = new char[10];
            }
            memcpy(buff, m_buff, 10)
            /*
            * Rest of the code handles shifting of the data and all
            **/
        }
    private:
        char* m_buff;
        int32_t m_len;
        int32_t m_read;
}

I'm not sure how can I make my original class use this mock class B's object rather than original class B inside my unittest (I'm using gtest, I' haven't included google test unit here). Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire