JaCoCo/EclEmma's Source highlighting function doesn't work when using PowerMock to Mock Constructor - highlight

I used PowerMock to Mock Constructor.Afer launching the application,I thought all lines shoud be green.However,actually all lines are red.
I think Mocking Constructor results in this phenomenon.Beacause mocking others,like final classes, is OK.How to fix this problem?
//code:
public class People {
public String sayHello(){
return "hello";
}
}
public class Family {
public String doEvent() {
People p = new People();
String str = p.sayHello();
System.out.println(str);
return str;
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(Family.class)
public class FamilyTest {
#Test
public void test() throws Exception {
Family f = new Family();
String str = "hello mock";
People p = PowerMock.createMock(People.class);
PowerMock.expectNew(People.class).andReturn(p);
EasyMock.expect(p.sayHello()).andReturn(str);
PowerMock.replay(p, People.class);
String strActual = f.doEvent();
Assert.assertEquals(str, strActual);
PowerMock.verify(p, People.class);
}
}

You shouldn't have to use #PrepareForTest unless you are mocking static methods inside that class.
I believe your issue is that when you prepare a class for test using Powermocks runner, it does something funky with the byte code, which EclEmma uses for line coverage. Since you are not mocking any static methods in your family class, try removing that from your #PrepareForTest.

Related

Spock : Verify Interaction Not working -- Too few Invocations

I have a very simple class as shown
class MyClass {
public static String getName(String input)
{
return toUpperCase(input);
}
public static String toUpperCase(String name)
{
return name.toUpperCase();
}
}
To test the above I have written a Test Case using Spock FW as shown below:
class MyClassTest extends Specification{
def 'check uppercase scnario'() {
given:
MyClass myClass = new MyClass();
when:
myClass.getName("test")
then: ""
1*myClass.toUpperCase("test");
}
}
But when I run this I see 0 Interactions
You cannot verify interactions on static Java methods. Just make your methods non-static. Besides, in the given: block, you are instantiating the class, so I guess you want to use instance methods anyway.
class MyClass {
public String getName(String input) {
return toUpperCase(input);
}
public String toUpperCase(String name) {
return name.toUpperCase();
}
}
Furthermore, if you wish to verify interactions on self-invocation calls, a Mock() is not what you need. Instead, simply use a Spy():
class MyClassTest extends Specification {
def 'check uppercase scnario'() {
given:
MyClass myClass = Spy()
when:
myClass.getName("test")
then:
1 * myClass.toUpperCase("test");
}
}
Try it in the Groovy Web Console.

Can i use a Factory to implement dependency injection

Someone told me that before dependency injection frameworks came around there developers would use a factory to implement DI. Can anyone provide an example how a factory pattern can be used for DI. I mean just by thinking about it a factory is a depenendency injector but i cant find any examples on the web.
This off the top of my head, untested code (with C#)
public class CarFactory : ICarFactory{
private static CarFactory instance = null;
public static ICarFactory SingletonInstance {
get {
if (this.instance == null){
this.instance = new CarFactory();
return this.instance;
}
},
set {
this.instance = value;
}
}
public ICar CreateCar(string make){
switch(make)
{
case "Toyota": return new Toyota();
case "Honda" : return new Honda();
default: throw new Exception();
}
}
}
public interface ICarFactory {
ICar CreateCar(string make);
}
public class Toyota : ICar
{
}
public class Honda : ICar
{
}
And usage would be something like :
ICar car = CarFactory.SingletonInstance.CreateCar("Toyota");
Exposing the singleton instance of the CarFactory publically enables you to mock the CarFactory for your unit tests and you can have your mocked CarFactory return mocked ICars when calling CreateCar.
Now replace the Cars in the factory by actual dependencies such as classes that implement services. And voila, you have a Factory that contains all your dependencies. You can now use the Factory to "resolve" your dependencies. You can take the example and push it further by using generic types and a dictionary (hashtable) where the key is the type name and the value the implementation instance such as:
public T Create<T>(){
return mydictionary.get(typeof(T).Name);
}
Something like that... You get the drift...
Hope it helps!

NUnit - Mock Repository and test with dummy data

I'm trying to establish a way of unit testing my service layer (& repositories) using some dummy data. I've seen examples of this before with Generic Repositories but I'm struggling to get something working whilst using a DatabaseFactory.
When I call the GetPhrase method from repository.Object I just get null back everytime.
I'm using NUnit and Moq. Any pointers on where i'm going wrong would be appreciated, or let me know if i'm better off going down a different road
e.g. Connecting to a local db for tests (SQL CE etc)
Here are the main components of the code:
public class PhraseRepository : RepositoryBase<Phrase>, IPhraseRepository
{
public PhraseRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
}
public string GetPhrase(string phraseCode)
{
return this.GetMany(p => p.PhraseCode == phraseCode).First().Descript;
}
}
public interface IPhraseRepository : IRepository<Phrase>
{
string GetPhrase(string phraseCode);
}
public class CLPRiskPhraseService : ICLPRiskPhraseService
{
private readonly IPhraseRepository phraseRepository;
public string GetPhrase(string phraseCode)
{
return phraseRepository.GetPhrase(phraseCode);
}
}
[Test]
public void GetPhrase()
{
var phrases = new FakePhraseData().GetPhrases();
phraseRepository.Setup(m => m.GetMany(It.IsAny<Expression<Func<Phrase, bool>>>())).Returns(phrases);
var result = phraseRepository.Object.GetPhrase("H300");
// Assert
NUnit.Framework.Assert.IsNotNull(phraseRepository.Object);
NUnit.Framework.Assert.AreEqual("Description0", result);
}
Invoking phraseRepository.Object.GetPhrase("H300") in your test will always return null unless you set it up to return something different.
I think you're mistakenly thinking that this call to GetPhrase will invoke GetMany like the concrete PhraseRepository does, but you need to remember that it's just a mock of the interface IPhraseRepository. A method on a mocked object will always return the default value of the return type (in this case string) unless you use Setup to change the behavior of that method.

Can I do piece-wise configuration of scoping for my objects in Ninject?

We have several cases where we are providing services in code libraries where we know scoping and lifetime rules for the service providers in the code library. We would like to configure that information in the library itself without having to have that knowledge bubbled up to the composition root.
I have been unable to figure out if it's possible to implement this with the current version of Ninject.
using System;
using System.Diagnostics.CodeAnalysis;
using Ninject;
using Ninject.Extensions.Conventions;
using NUnit.Framework;
using Ninject.Modules;
[TestFixture]
public class Spike
{
private IKernel kernel;
[SetUp]
public void SetUp()
{
this.kernel = new StandardKernel();
this.kernel.Load(new Registry());
this.kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.BindAllInterfaces()
);
}
[TearDown]
public void TearDown()
{
Thing1.ResetCounts();
}
[Test]
public void GetThing1AndThing2()
{
// arrange
var thing1 = this.kernel.Get<Thing1>();
var thing2 = this.kernel.Get<Thing1>();
// act
thing1.DoTheWork();
thing2.DoTheWork();
// assert
Assert.AreEqual(1, Thing1.ConstructorCount, "wrong number of constructor invocations");
Assert.AreEqual(2, Thing1.DoTheWorkCount, "wrong number of method invocations");
}
[Test]
public void GetIThing1AndIThing2()
{
// arrange
var thing1 = this.kernel.Get<IThing1>();
var thing2 = this.kernel.Get<IThing1>();
// act
thing1.DoTheWork();
thing2.DoTheWork();
// assert
Assert.AreEqual(1, Thing1.ConstructorCount, "wrong number of constructor invocations");
Assert.AreEqual(2, Thing1.DoTheWorkCount, "wrong number of method invocations");
}
public class Registry : NinjectModule
{
public override void Load()
{
Bind<Thing1>().ToSelf().InSingletonScope();
}
}
public interface IThing1
{
void DoTheWork();
}
public class Thing1 : IThing1
{
public static int ConstructorCount { get; set; }
public static int DoTheWorkCount { get; set; }
public Thing1()
{
Console.WriteLine("Thing1.ctor underway");
++Thing1.ConstructorCount;
}
public void DoTheWork()
{
Console.WriteLine("Thing1.DoTheWork underway");
++Thing1.DoTheWorkCount;
}
public static void ResetCounts()
{
Thing1.ConstructorCount = 0;
Thing1.DoTheWorkCount = 0;
}
}
}
In this test case, the ilbrary is represented by the Registry, Thing1, and IThing1 classes. The user of the library is the test fixture, where the Spike.SetUp() method shows the code we'd ideally like the library user to write (where they'd pass in a path containing the dll instead of new-ing up a Registry object).
With the code as written, fetching the Thing1 service multiple times in Spike.GetThing1AndThing2() exhibits the desired singleton behavior. Fetching the Thing1 service multiple times via its published interface as in Spike.GetIThing1AndIThing2() does not exhibit singleton behavior but rather constructs two separate Thing1 objects.
So is it possible to do what I'm asking: to specify the singleton behavior in the DLL itself while having the scan performed when the composition root is formed?
You need to introduce conventions. E.g. Add an attribute specifying the scope or use a naming convention so that you can identify the scope from the name.
Then setup the binding conventions correctly. E.g
this.kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.WithAttribute<SingletonAttribute>()
.BindAllInterfaces()
.Configure(binding => binding.InSingletonScope());
this.kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.WithAttribute<TransientAttribute>()
.BindAllInterfaces());

Unit Testing on a Repository with Generic Parameters

Let's say I have a Generic Repository class along the lines of the following:
public class Repository<T> : IRepository<T> where T : class
{
IObjectSet<T> source;
public Repository(IUnitOfWork transactionHandler)
{
source = transactionHandler.CreateObjectSet<T>();
}
public IQueryable<T> GetAll()
{
return source.AsQueryable<T>();
}
public void Add(T entity)
{
source.AddObject(entity);
}
//blah blah other methods
}
I am having trouble wrapping my mind around how (or even if?) I would unit test this.
Visual Studio generates a combo of tests that I can understand for the above implementation of GetAll
public void GetAllTest()
{
GetAllTestHelper<SomeExpectedType>();//expect this to pass
try
{
GetAllTestHelper<SomeUnexpectedType>();//expect this to throw exception
}
//catch exception - check it is expected type etc.
}
public void GetAllTestHelper<T>() where T : class
{
IUnitOfWork transactionHandler = IUnitOfWorkFactory.GetUnitOfWork();
Repository<T> target = new Repository<T>(transactionHandler);
IQueryable<T> actual = target.GetAll();
Assert.IsInstanceOfType(actual, typeof(IQueryable<T>));
}
The idea being - I can prove that calling this method returns an IQueryable of type T. I can also prove that it throws an InvalidOperationException for a type that an IObjectSet cannot be generated for (also required/desired).
For the Add method I am going round in circles.
For the 'why' - why have a test - I think I want to prove that I can add a type of T to the repository and then prove it has been added to the DB.
For the 'how' - using the VS default as above, I get something along the lines of
public void AddTest()
{
AddTestHelper<SomeExpectedType>();
}
public void AddTestHelper<T>() where T : class
{
IUnitOfWork transactionHandler = UnitTestHelper.GetUnitOfWork();
Repository<T> target = new Repository<T>(transactionHandler);
T entity = default(T);
target.Add(entity);//throws exception - value cannot be null
}
So my question is
a) how would you unit test this repository?
or possibly
b) would you test this repository?
a) how would you unit test this repository?
A mock framework such as Rhino Mocks or Moq could simplify the task of unit testing this class. It would be used to mock the IUnitOfWork interface that is passed to the constructor of the repository.
For example here's how a typical unit test of the Add method for this repository might look like using Rhino Mocks:
[TestMethod]
public void Add_Should_Use_AddObject_On_Underlying_Source()
{
// arrange
var uofStub = MockRepository.GenerateStub<IUnitOfWork>();
var objectSet = MockRepository.GenerateStub<IObjectSet<string>>();
uofStub.Stub(x => x.CreateObjectSet<string>()).Return(objectSet);
var sut = new Repository<string>(uofStub);
var entity = "foo bar";
// act
sut.Add(entity);
// assert
objectSet.AssertWasCalled(x => x.AddObject(entity));
}
As far as the automatic combo of tests generated by Visual Studio are concerned IMHO that's probably one of the most useless ever feature in VS.
b) would you test this repository?
Yes, absolutely.

Resources