Mock Method2 of Interface called in another method1 - unit-testing

I am writing unit tests for Method1()
I want to mock Method2() that is called from Method1() of the same interface.
We can mock methods of another interface easily by taking that mocked implementation in the struct. But I'm not sure how to mock a method of the same interface.
type ISample interface {
Method1()
Method2()
}
type Sample struct {
}
func (s Sample) Method1() {
s.Method2()
}
func (s Sample) Method2() {
}

Can be solved by using an embedded interface.
type ISample interface {
Method1()
Method2()
}
type Sample struct {
ISample
}
func (s Sample) Method1() {
s.ISample.Method2()
}
func (s Sample) Method2() {
}
While creating an object of Sample, assign mocked ISample to ISample.

Related

Google Test on a local function that calls another function

I have a class that I want to test.
class Myclass {
virtual int functionA (int x) {
if (x==1) {
functionB();
return 1;
}
else return 0;
}
virtual void functionB() {
// do some logic
functionC();
printf ("functionB \n"};
}
virtual void functionC() {
// do some logic
printf ("functionC \n"};
}
}
I setup a Mock class:
class MockMyClass : public Myclass {
MOCKMETHOD1(functionA, int(int x));
MOCKMETHOD0(functionB, void());
MOCKMETHOD0(functionC, void());
}
My test case in test class:
class MyTesting : public testing::Test {
virtual void SetUp(){
testObj = new MyClass();
testMock = new MockMyClass();
}
virtual void Teardown() {
delete testObj;
delete testMock;
}
}
MyClass * testObj;
MockMyClass * testMock;
TEST_F (MyClass, Test1){
EXPECT_CALL (testMock, functionB());
testObj->functionA()
}
TEST_F (MyClass, Test2){
EXPECT_CALL (testMock, functionC());
testObj->functionB()
}
TEST_F (MyClass, Test3){
EXPECT_CALL (testMock, functionC());
testObj->functionC()
}
Basically, I need to run the functionA -> functionB -> functionC.
How can write Test1 such that when have expect call of functionB, it doesn't "go further" into B and requires another expect call of function C.
In other words, how can write a Test1 such that whatever logic in functionB will be tested in Test2 and further in Test3 and Test1 just expect a call of functionB.
TEST_F (MyClass, Test1) {
InSequence seq;
EXPECT_CALL (MockMyClass, functionB());
EXPECT_CALL (MockMyClass, functionC());
testObj->functionA(1);
}
InSequence
Your example will not compile, functionA requires arg and missing semicolons.
Wrong use of inheritance is main problem here.
If your class under test is same as mock class then this should be obvious something wrong is here.
Note that here:
virtual void SetUp() {
testObj = new MyClass();
testMock = new MockMyClass();
}
there is no dependency between testObj and testMock. So Question is how testObje can impact state of testMock? It can't!
So basically problem is your code design of production code (code under test).
Since logic of this class has been obfuscated I have no clues how I could fix your code properly. I'm guessing it should be something like this:
class ISomeDependency {
public:
virtual int functionA(int x) = 0;
};
//---------
class Myclass {
public:
Myclass(ISomeDependency& dep)
: mDep { dep }
{
}
void functionB()
{
if (mDep.function(1) > 5) {
functionC();
}
}
void functionC()
{
}
private:
ISomeDependency& mDep;
};
class MyclassTest : public ::testing::Test {
void checkMyClassIsInStateX()
{
ASSERT_EQ(myClass.getX(), ...);
}
public:
MockSomeDependency mock;
Myclass myClass { mock };
};
TEST_F(MyclassTest, functionBCallsDependencyWithOneAndChangesStateToX)
{
EXPECT_CALL(mock, functionA(1)).WillOnce(Return(4));
myClass.functionB();
checkMyClassIsInStateX();
}

Factory Pattern w/ Gmock

I have a interface where I am using the factory pattern to create an instance of the object and store it in a unique_ptr. I also have a MockInterface which I would like to use in my tests to not call the actual production code. However when I run my tests the production interface is called instead of the mock. What am I doing wrong??
Interface.hpp
class Interface
{
Interface() {};
virtual ~Interface() = default;
virtual int foo() = 0;
virtual int bar() = 0;
static std::unique_ptr<Interface> create();
};
Interface.cpp
#include "Interface.hpp"
#include "Impl.hpp"
std::unique_ptr<Interface> Interface::create()
{
return std::unique_ptr<Interface> { new Impl() };
}
Impl.hpp
class Impl : public Interface
{
Impl() {};
~Impl() {};
virtual int foo();
virtual int bar();
};
Impl.cpp
#include "Interface.hpp"
#include "Impl.hpp"
int Impl::foo()
{
return 2;
}
int Impl::bar()
{
return 2;
}
class MockInterface : public Interface
{
MockInterface() {};
~MockInterface() {};
MOCK_METHOD(int, foo, (), (override));
MOCK_METHOD(int, bar, (), (override));
}
lib.cpp
#include "Interface.hpp"
class Foo
{
public:
Foo() { inst = Interface::create(); }
virtual ~Foo() = default;
void some_function();
private:
std::unique_ptr<Interface> inst;
}
void Foo::some_function()
{
int foo_ret = inst->foo();
int bar_ret = inst->bar();
}
test.cc
std::unique_ptr<Interface> Interface::create()
{
std::unique_ptr<MockInterface> mock { new MockInterface() };
EXPECT_CALL(*mock, foo()).Times(1);
EXPECT_CALL(*mock, bar()).Times(1);
return mock;
}
TEST_F(fixture, test_foo)
{
// This will pass but I will get an error "mock object never deleted"
// Will also leave my terminal in a bad state
Foo *obj = new Foo();
obj->some_function();
// This will fail also leaving my terminal in a bad state
Foo obj2;
obj2.some_function();
}
some_function() calls Interface::create(), which has not been mocked, so it's still going to give you back a unique pointer pointing to an Impl object, not a MockInterface object.
To solve this you can either mock out Interface::create to have it return your mocked object, or have some_function receive a pointer/reference to Interface as a parameter instead of calling Interface::create itself. Then just pass it your mocked object.
The simplest way to mock the create function is to just redefine it for your tests. Exclude Interface.cpp from your test program since the function can only be defined once
std::unique_ptr<Interface> Interface::create()
{
std::unique_ptr<MockInterface> mock { new MockInterface() };
EXPECT_CALL(*mock, foo()).Times(1);
return mock;
}
TEST_F(fixture, test_foo)
{
some_function();
}
To provide different implementations for each test you can do something like this:
std::function<std::unique_ptr<Interface>()> creator;
std::unique_ptr<Interface> Interface::create()
{
return creator();
}
TEST_F(fixture, test_foo)
{
creator = []() {
std::unique_ptr<MockInterface> mock { new MockInterface() };
EXPECT_CALL(*mock, foo()).Times(1);
return mock;
};
// Will call Interface::create which will call creator()
some_function();
}

How to write unit test case for Dispose method

I want to cover my dispose method in unit test (using nunit framework), written inside repository
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_bpRioCostCentreContext.Dispose();
}
_disposed = true;
}
~CostCentreRepository()
{
Dispose(false);
}

Bring object through interface in order to mock it

I am at a somewhat of a crossroads with the following issue. I have, let's say, the following class
public class Foo
{
internal Bar bar { get; }
internal Foo(Bar bar)
{
this.bar = bar;
}
}
and I am trying to a Unit test of it using XUnit and Moq. The initial test I created was
[Theory]
[AutoMockData]
internal void CtorShouldCreateInstance(Bar bar)
{
var sut = new Foo(bar);
Assert.NotNull(sut);
}
which was a valid unit test, but by passing Bar as a parameter it bring all it's dependencies making it as a concrete type. The suggestion from my colleague was to bring the Bar object through an Interface and Mock the interface but I am not sure how to do it.
I've thought of making the interface, a method to CreateBar with its required parameters, inherit the interface to the Foo class, implement the method and then add it to the unit test, but I've wanted to get a clarification or approval as I am not sure this is the correct way.
Thanks in advance for all the help!
You have to derive Bar from IBar, so then you can Mock it easily with Mocking framework like FakeItEasy, here is an example :
public interface IBar
{
string SayHello();
}
public class Bar : IBar
{
public string SayHello()
{
// A complex work to retrieve data from external resource
return "Hello";
}
}
public class Foo
{
private readonly IBar _bar;
public Foo(IBar bar)
{
_bar = bar;
}
public string Greeting()
{
return _bar.SayHello();
}
}
Now you can mock IBar to return your desired result :
[TestFixture]
public class FooTests
{
[Test]
public void Bar_ShouldReturn_HiInsteadOfHello()
{
IBar fakeBar = A.Fake<IBar>();
A.CallTo(() => fakeBar.SayHello()).Returns("Hi");
Foo sut = new Foo(fakeBar);
Assert.AreEqual(sut.Greeting(), "Hi");
}
}
* Side note: You can also Mock your method directly without deriving that from an interface by making that virtual, but as a best practice it's better to use interfaces instead :
public class Bar
{
public virtual string SayHello()
{
// A complex work to retrieve data from external resource
return "Hello";
}
}
public class Foo
{
private readonly Bar _bar;
public Foo(Bar bar)
{
_bar = bar;
}
public string Greeting()
{
return _bar.SayHello();
}
}
[TestFixture]
public class FooTests
{
[Test]
public void Bar_ShouldReturn_HiInsteadOfHello()
{
Bar fakeBar = A.Fake<Bar>();
A.CallTo(() => fakeBar.SayHello()).Returns("Hi");
Foo sut = new Foo(fakeBar);
Assert.AreEqual(sut.Greeting(), "Hi");
}
}
Apparently all I had to do was to pass the IBar interface as the parameter instead of the normal Bar class, because AutoMockData took care of everything.
So yeah the answer was to make the Foo class
public class Foo
{
internal IBar bar { get; }
internal Foo(Bar bar)
{
this.bar = bar;
}
}
and the test becomes
[Theory]
[AutoMockData]
internal void CtorShouldCreateInstance(IBar bar)
{
var sut = new Foo(bar);
Assert.NotNull(sut);
}
Thanks everyone for all the help!

How do you unit test an interface?

For example, there is a interface IMyInterface, and three classes support this interface:
class A : IMyInterface
{
}
class B : IMyInterface
{
}
class C : IMyInterface
{
}
In the simplest way, I could write three test class : ATest, BTest, CTest and test them separately. However, since they support the same interface, most test code would be the same, it's hard to maintain. How can I use a simple and easy way to test a interface that is supported by different class?
(previously asked on the MSDN forums)
If you want to run the same tests against different implementers of your interface using NUnit as an example:
public interface IMyInterface {}
class A : IMyInterface { }
class B : IMyInterface { }
class C : IMyInterface { }
public abstract class BaseTest
{
protected abstract IMyInterface CreateInstance();
[Test]
public void Test1()
{
IMyInterface instance = CreateInstance();
//Do some testing on the instance...
}
//And some more tests.
}
[TestFixture]
public class ClassATests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new A();
}
[Test]
public void TestCaseJustForA()
{
IMyInterface instance = CreateInstance();
//Do some testing on the instance...
}
}
[TestFixture]
public class ClassBTests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new B();
}
}
[TestFixture]
public class ClassCTests : BaseTest
{
protected override IMyInterface CreateInstance()
{
return new C();
}
}
To test an interface with common tests regardless of implementation, you can use an abstract test case, and then create concrete instances of the test case for each implementation of the interface.
The abstract (base) test case performs the implementation-neutral tests (i.e. verify the interface contract) while the concrete tests take care of instantiating the object to test, and perform any implementation-specific tests.
Could create methods that take a parameter of type IMyInterface and have the actual test methods just call those methods passing in different concrete classes.
You do not test the interface directly, but you may write an abstract class that tests the contract a particular implementation should extend. A test of a concrete class would then extend the abstract class
If you're using NUnit, then you could use Grensesnitt:
public interface ICanAdd {
int Add(int i, int j); //dont ask me why you want different adders
}
public class winefoo : ICanAdd {
public int Add(int i, int j)
{
return i + j;
}
}
interface winebar : ICanAdd {
void FooBar() ;
}
public class Adder1 : winebar {
public int Add(int i, int j) {
return i + j;
}
public void FooBar() {}
}
public class Adder2 : ICanAdd {
public int Add(int i, int j) {
return (i + 12) + (j - 12 ); //yeeeeeaaaah
}
}
[InterfaceSpecification]
public class WithOtherPlugins : AppliesToAll<ICanAdd>
{
[TestCase(1, 2, 3)]
[TestCase(-1, 2, 1)]
[TestCase(0, 0, 0)]
public void CanAddOrSomething(int x, int y, int r)
{
Assert.AreEqual(subject.Add(x, y), r);
}
[TestCase(1, 2, Result = 3)]
[TestCase(-1, 2, Result = 1)]
[TestCase(0, 0, Result = 0)]
public int CannAddOrSomethingWithReturn(int x, int y) {
return subject.Add(x, y);
}
}