How to write mock for structs in Go - unit-testing

I want to write a unit test for the Transport function which will require mocking CarFactory and Car structs. See the following code:
package main
type Car struct {
Name string
}
func (h Car) Run() { ... }
type CarFactory struct {}
func (e CarFactory) MakeCar() Car {
return Car{}
}
func Transport(cf CarFactory) {
...
car := cf.MakeCar()
car.Run()
...
}
In other OOP languages like Java, C# or C++, I can just define CarFactoryMock and CarMock that extend CarFactory and Car then override MakeCar() method to return a CarMock object
class CarMock extends Car {
public Run() {...}
}
class CarFactoryMock extends CarFactory {
public Car MakeCar() { return new CarMock(); }
}
Transport(new CarFactoryMock())
How do I achieve this in Go?
Note that I can change prototype and source code of Transport function, but must keep CarFactory and Car the same since they are taken from a 3rd package
The last code snippet was about Human and Employee, which lead to confusion`.

It takes more code to mock a struct in Go than other OOP languages that support full late binding.
This code must remain untouched since its taken from a 3rd party:
type Car struct {
Name string
}
func (c Car) Run() {
fmt.Println("Real car " + c.Name + " is running")
}
type CarFactory struct {}
func (cf CarFactory) MakeCar(name string) Car {
return Car{name}
}
Since Go only supports late binding on interface, I had to make Transport receive an interface as a parameter instead of a struct:
type ICar interface {
Run()
}
type ICarFactory interface {
MakeCar(name string) ICar
}
func Transport(cf ICarFactory) {
...
car := cf.MakeCar("lamborghini")
car.Run()
...
}
And here are the mocks:
type CarMock struct {
Name string
}
func (cm CarMock) Run() {
fmt.Println("Mocking car " + cm.Name + " is running")
}
type CarFactoryMock struct {}
func (cf CarFactoryMock) MakeCar(name string) ICar {
return CarMock{name}
}
Now I can easily use the mock Transport(CarFactoryMock{}). But when I try to call the real method Transport(CarFactory{}), the go compiler shows me the following errors:
cannot use CarFactory literal (type CarFactory) as type ICarFactory in argument to Transport:
CarFactory does not implement ICarFactory (wrong type for MakeCar method)
have MakeCar(string) Car
want MakeCar(string) ICar
As the message says, MakeCar function from the interface returns an ICar, but the real MakeCar returns a Car. Go doesn't allow that. To walk around this problem I had to define a wrapper to manually convert Car to ICar.
type CarFactoryWrapper struct {
CarFactory
}
func (cf CarFactoryWrapper) MakeCar(name string) ICar {
return cf.CarFactory.MakeCar(name)
}
Now you can call the Transport function like this: Transport(CarFactoryWrapper{CarFactory{}}).
Here is the working code https://play.golang.org/p/6YyeZP4tcC.

You use an interface.
type Employee interface {
GetHuman() Human
}
type RealEmployee struct {
Company string
h Human
}
func (e RealEmployee) GetHuman() Human {
return e.h
}
// Call Hire with real employee
Hire(RealEmployee{h: RealHuman})
Hire method accepts the interface Employee, then you can write one MockEmployee struct in your tests.
func Hire(e Employee) {
...
h := e.GetHuman()
fmt.Println(h.Name)
...
}
// Mock Employee instance
type MockEmployee struct {
Company string
h Human
}
func (m MockEmployee) GetHuman() Human {
return m.h
}
// Call Hire to test with mock employee
Hire(MockEmployee{h: MockHuman})

Related

Open Generics with injected primitive

How can I register an Open Generic type with another open generic and primitive injected in the constructor?See example below.In this example, Resolve is throwing "Unable to resolve String as parameter "connectionString"" exception. (you can check live code here)
using System;
using DryIoc;
public class Program
{
public static void Main()
{
var container = new Container();
container.RegisterInstance("some_connection_string", serviceKey: "connectionString");
container.Register(typeof(Configuration<>), Reuse.Singleton);
container.Register(typeof (IEntityUpdater<>), typeof (SqlEntityUpdater<>), Reuse.Singleton);
var p = container.Resolve<IEntityUpdater<EventArgs>>();
Console.WriteLine(p);
}
}
public class Configuration<T> where T : class { }
internal interface IEntityUpdater<in T> where T : class
{
void Update(T entity);
}
internal class SqlEntityUpdater<T> : IEntityUpdater<T> where T : class
{
public SqlEntityUpdater(Configuration<T> configuration, string connectionString)
{
}
public void Update(T entity) { }
}
First, RegisterInstance is depricated, use UseInstance.
Second, the actual problem is that you registering instance with serviceKey and nowhere using this key for injection.
So, you either remove the serviceKey parameter.
Or, specify the key on injection side:
container.Register(typeof(IEntityUpdater<>), typeof(SqlEntityUpdater<>), Reuse.Singleton,
made: Parameters.Of.Type<string>(serviceKey: "connectionString"));

How to implement nested fluent interface?

I have a task to implement fluent interface for a class, which consist of other classes. Let's say we have a class:
class Pizza {
int price, size;
}
class Foo {
string name;
Pizza p1, p2;
}
I would like to use code like:
Foo f = FooBuilder().setName("foo")
.settingP1().setPrice(5).setSize(1)
.settingP2().setPrice(2)
.build();
but I also would like to forbid code like:
Foo f = FooBuilder().setName("foo").setPrice(5);
I thought about a class inherited from FooBuilder which is returned after calling .settingP1() but I am not sure how to do it. Notice that I don't want to write .build() when I ended specifying Pizza object.
EDIT: Maybe I should've mentioned that when I wrote .settingP2().setPrice(2) without writing .setSize(sth) I meant that size will just have default value. I want to be able to "jump" to the next object regardless of specifying all attributes or not
EDIT2: I know how to implement the Builder pattern and fluent interface for classes which have fields of basic types. The problem is I want the code
Foo f = FooBuilder().setName("foo").setPrice(5);
to not compile. Maybe it's impossible to write such a builder.
If you don't mind, I'll write solution for your problem in Java, hopefully you'll be able to apply it in C++ without anyu problem.
You have 2 options.
More verbose DSL (I prefer not to call your problem Builder any more, but either Fluent API, or DSL - Domain Specific Language, as it defines grammar rules for it) with simpler implementation
or simpler DSL (exactly what you wrote) with a small trick in the implenmentation.
For optiona #1 your usage would look like this:
new FooBuilder().setName("Foo")
.settingP1().setPrice(5).setSize(1).end()
.settingP2().setPrice(2).end()
.build();
Notice additional methods end(). Corresponding code in Java would look like this:
public class FooBuilder {
public FooBuilder setName(String name) {
// Store the name
return this;
}
public PizzaBuilder settingP1() {
return new PizzaBuilder(pizza1, this);
}
public PizzaBuilder settingP2() {
return new PizzaBuilder(pizza2, this);
}
public Foo build() {
// return Foo build using stored information
}
}
public class PizzaBuilder {
private final Pizza pizza;
private final FooBuilder foo;
// Constructor
public PizzaBuilder(Pizza pizza, FooBuilder foo) {
this.pizza = pizza;
this.foo = foo;
}
public PizzaBuilder setPrice(int price) {
// update pizza price
return this;
}
public PizzaBuilder setSize(int size) {
// update pizza size
return this;
}
// With this method you return to parent, and you can set second pizza.
public FooBuilder end() {
return foo;
}
}
Now for option #2 I'd do another generalization to your problem to allow defining any number of pizzas. I'd also omit set prefix, it's not usual for DSL:
new FooBuilder().name("Foo")
.addPizzaWith().price(5).size(1)
.addPizzaWith().price(2)
.build();
Now the implementation will look like:
public class FooBuilder {
public FooBuilder(String name) {
// Store name
return this;
}
public PizzaBuilder addPizzaWith() {
Pizza pizza = createAndStorePizza(); // Some private method to do what is says
return new PizzaBuilder(pizza, this);
}
public Foo build() {
// Build and return the Foo using stored data
}
}
public class PizzaBuilder {
private final Pizza pizza;
private final FooBuilder foo;
public PizzaBuilder(Pizza pizza, FooBuilder foo) {
this.pizza = pizza;
this.foo = foo;
}
public PizzaBuilder price(int value) {
// Store price value
return this;
}
public PizzaBuilder size(int value) {
// Store size value
return this;
}
// This method does the trick - it terminates first pizza specification,
// and delegates entering second (or any other) pizza specification to
// the parent FooBuilder.
public PizzaBuilder addPizzaWith() {
return foo.addPizzaWith();
}
// Another similar trick with allowing to call build directly on Pizza
// specification
public Foo build() {
return foo.build();
}
}
There is one noticeable attribute - circular dependency. FooBuilder must know PizzaBuilder, and PizzaBuilder must know FooBuilder. In Java it's not an issue.
If I remember correctly, you can solve it in C++ too by declaring first just the
type using forward declaration or so.
It would also be typically beneficial for the second example in Java to introduce an interface with methods build() and addPizzaWith(), which both classes implement. So you can e.g. add pizzas in cycle without any issue.
Dmitri Nesteruk has written a "facet builder" example that is pretty much what you are trying to achieve.
The basic structure would be something like (almost pseudo code):
class FooBuilderBase {
protected:
Foo& foo; // reference to derived builders
FooBuilderBase(Foo& f) : foo(f) {}
public:
PizzaBuilder settingP1() { return PizzaBuilder(foo, foo.p1); }
PizzaBuilder settingP2() { return PizzaBuilder(foo, foo.p2); }
};
class FooBuilder : public FooBuilderBase {
Foo foo_; // real instance
public:
FooBuilder() : FooBuilderBase(foo_) {}
FooBuilder& setName(string n) { foo.name = n; return *this; }
};
class PizzaBuilder : public FooBuilderBase {
Pizza& pizza;
public:
PizzaBuilder(Foo& f, Pizza& p) : FooBuilderBase(f), pizza(p) {}
PizzaBuilder& setPrice(int p) { pizza.price = p; return *this; }
};
You can add a FooPizzaBuilder class as derrivate of FooBuilder.
By doing this you seperate the building of your Pizza classes and the building of the actual Foo class.
Consider the following code:
enum class PizzaNum {
ONE, TWO
}
class FooPizzaBuilder;
class FooBuilder {
public:
FooBuilder();
FooBuilder setName();
FooPizzaBuilder settingP1();
FooPizzaBuilder settingP2();
Foo build();
protected:
void _setPrize(PizzaNum); //Don't expose _setPrice() to user
void _setSize(PizzaNum); //Don't expose _setSize() to user
}
class FooPizzaBuilder : public FooBuilder {
public:
FooPizzaBuilder(PizzaNum pizzaNum)
FooPizzaBuilder setPrice(); //Call _setPrice()
FooPizzaBuilder setSize(); //Call _setSize()
}
This requires you to call settingP1() before making a call to setPrice();
An easy way to make the code type safe is to add an enum class to FooBuilder.
class FooBuilder {
public:
enum class PizzaNum {
ONE,
TWO
}
}
and...
FooBuilder& FooBuilder::setPrice(const PizzaNum pizzaNum, const int price) {
switch (pizzaNum) {
case PizzaNum::ONE:
p1.setPrice(price);
break;
case PizzaNum::TWO:
p2.setPrice(price);
break;
}
return this;
}
Then, you need to pass the enum to the method otherwise it results in a compile time error (e.g. .setPrice(FooBuilder::PizzaNum::ONE, 5).
Note, this is non-variadic.

Why doesn't dynamic partial mocking work for JMockit's #Injectable?

In the following test case where no Expectations have been recorded, I would expect that the dynamic partial mocking feature will be used for the fields A and B which are initialized in UnitToTest using #Injectable. But instead always the method calls are mocked. Only using an invalid filter value for static partial mocking, it is possible to call the real methods:
#Service
class A {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
#Service
class B {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
#Service
class UnitToTest {
#Autowired B b;
#Autowired A a;
public B getB() { return b; }
public A getA() { return a; }
}
public class TestClass {
#Tested UnitToTest unit;
// #Mocked({ "someInvalidFilter()" })
#Injectable A a;
// #Mocked({ "someInvalidFilter()" })
#Injectable B b;
#Test
public void test() {
// actual return value is always null if no invalid static partial
// mocking filters are specified above
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}
For me it looks like dynamic partial mocking with JMockit doesn't work for #Injectables. Is that a known restriction?
#Injectables always get injected into #Tested objects, assuming a matching field or constructor parameter can be found; the injection process even takes into consideration DI annotations such as #Inject and #Autowired.
However, an #Injectable instance is always created as an uninitialized (ie, with no state) and fully mocked instance. Partial mocking, on the other hand, is meant for real instances that you instantiate (and initialize) yourself in the test.
So, what you seem to be asking for is that said real instances (partially mocked or not) could be injected into #Tested objects. Indeed, this is not supported (except by calling Deencapsulation.setField), since a motivating use case was never presented by users.
That said, the example test will pass if it is changed to the following:
public class TestClass {
#Tested(fullyInitialized = true) UnitToTest unit;
#Test
public void test() {
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}
The above is an integration test, though, not a unit test.

How can I create and use a partial stub (in MoQ) without being tied to the concrete implimentation?

I have code that uses MoQ to create a partial stub. I'd prefer to interact with the interface instead of the concrete implementation so that I won't have to modify the unit test if I have a different implementation of the interface.
So for example, I have a factory method such as:
private Mock<ISomeInterface> ISomeInterfaceStubFactory()
{
return new Mock<SomeConcreteImplementation>();
}
Here is the code that calls the method:
var partialStub = ISomeInterfaceStubFactory();
partialStub.Setup(m => m.MethodToStubOutThatMethodToTestCalls(It.IsAny<string>())).Returns(new List<SomeOtherObject>());
partialStub.CallBase = true;
var actualResult= partialStub.Object.MethodToTest();
Assert.That(actualResult, Is.EqualTo(expectedResult));
The problem is that when doing this is that ISomeInterfaceStubFactory won't compile. So I changed it to be like below, but doing this seems to break the partial stub. The actual implemented MethodToStubOutThatMethodToTestCalls operation gets called, not the stubbed version. Basically I'm trying to use polymorphism with the stub object. Is there anyway to do this? I'd like my unit test to not be highly coupled to the concrete implementation.
private Mock<ISomeInterface> ISomeInterfaceStubFactory()
{
return new Mock<SomeConcreteImplementation>.As<ISomeInterface>();
}
I think you are missing the point of mock objects. Returning a mock from a concrete implementation makes no sense. The idea is to have the class under test depend on some interface or abstract which you could mock.
Revising my answer per your clarification. I don't disagree with arootbeer, but I do want to understand what you are doing and why it doesn't work.
Here's a simple example of what I think you are trying to do. The test passes for me for both concrete implementations. Is this what you are trying to do, and does this example work for you?
Interface and classes:
using System;
namespace ClassLibrary1
{
public interface IFoo
{
string GetBaseString();
string GetExtendedString();
}
public class Foo_A : IFoo
{
public virtual string GetBaseString()
{
return "Foo_A";
}
public virtual string GetExtendedString()
{
return GetBaseString() + "_Bar";
}
}
public class Foo_B : IFoo
{
public virtual string GetBaseString()
{
return "Foo_B";
}
public virtual string GetExtendedString()
{
return GetBaseString() + "_Bar";
}
}
}
Unit test:
using System;
using Xunit;
using Moq;
namespace ClassLibrary1.UnitTests
{
public class Class1
{
[Fact]
public void GetExtendedString_ReturnsExtendedString()
{
var partialFoo = IFooFactory();
partialFoo.Setup(x => x.GetBaseString()).Returns("Foo");
partialFoo.CallBase = true;
string result = partialFoo.Object.GetExtendedString();
Assert.Equal("Foo_Bar", result);
}
private Mock<IFoo> IFooFactory()
{
return new Mock<Foo_A>().As<IFoo>();
//return new Mock<Foo_B>().As<IFoo>();
}
}
}

Parametric test with generic methods

In NUnit 2.5 you can do this:
[TestCase(1,5,7)]
public void TestRowTest(int i, int j, int k)
{
Assert.AreEqual(13, i+j+k);
}
You can do parametric test.
But I wonder whether you can do this or not, parametric test with generic test method? I.e.:
[TestCase <int>("Message")]
public void TestRowTestGeneric<T>(string msg)
{
Assert.AreEqual(5, ConvertStrToGenericParameter<T>(msg));
}
Or something similar.
Here is the quote from the release note of NUnit 2.5 link text
Parameterized test methods may be
generic. NUnit will deduce the correct
implementation to use based on the
types of the parameters provided.
Generic test methods are supported in
both generic and non-generic clases.
According to this, it is possible to have generic test method in non-generic class. How?
I don't quite understand Jeff's comment. In .net generics is both compile-time and run-time. We can use the reflection to find out the test case attribute associated with a method, find out the generic parameter, and again use reflection to call the generic method. It will work, no?
Update: OK, I now know how and hope it is not too late. You need the generic type to be in the parameter list. For example:
[TestCase((int)5, "5")]
[TestCase((double)2.3, "2.3")]
public void TestRowTestGeneric<T>(T value, string msg)
{
Assert.AreEqual(value, ConvertStrToGenericParameter<T>(msg));
}
You can make custom GenericTestCaseAttribute
[Test]
[GenericTestCase(typeof(MyClass) ,"Some response", TestName = "Test1")]
[GenericTestCase(typeof(MyClass1) ,"Some response", TestName = "Test2")]
public void MapWithInitTest<T>(string expectedResponse)
{
// Arrange
// Act
var response = MyClassUnderTest.MyMethod<T>();
// Assert
Assert.AreEqual(expectedResponse, response);
}
Here is implementation of GenericTestCaseAttribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
{
private readonly Type _type;
public GenericTestCaseAttribute(Type type, params object[] arguments) : base(arguments)
{
_type = type;
}
IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
{
if (method.IsGenericMethodDefinition && _type != null)
{
var gm = method.MakeGenericMethod(_type);
return BuildFrom(gm, suite);
}
return BuildFrom(method, suite);
}
}
Create a private method and call that:
[Test]
public void TypeATest()
{
MyTest<TypeA>();
}
[Test]
public void TypeBTest()
{
MyTest<TypeB>();
}
private void MyTest<T>()
{
// do test.
}