I have constructor where there is filter logic and wanna test it, though writing test case for constructor is not in practice i wanna have the code coverage , have tried many links but none are explaining about handling a constructor.
public Myclass {
public Myclass(AnotherClass obj)
{
_key = obj.key;
_ID = obj.ID;
_CandidateMode = obj.CandidateMode;
if(_CandidateMode == obj.CandidateMode.numeric
{
//Dosomething
}
else
{
//Do something with special character.
}
}
}
Definitely placing logic inside a constructor is a thing to avoid. Good you know that :-) In this particular case maybe the if could go into each of the public methods of MyClass, or maybe you could use polymorphism (create MyClass or MySpecialCharacterClass base on the AnotherClass object)?
Anyway, to get to a straight answer: if you really must test constructor logic, do it like you would test any other method (in some languages it's just a static method called new, by the way).
[TestMethod]
public void is_constructed_with_numeric_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.numeric };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for numeric candidate
...
}
[TestMethod]
public void is_constructed_with_special_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.special };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for special candidate
...
}
I'm trying to do a test on my controllers which get data from repository classes.
This is the part of the repository I want to test:
public class NewsRepository
{
public IEnumerable<NewsItem> GetNews()
{
var result = (from n in n_db.NewsItems
orderby n.ID descending
select n).Take(3);
return result;
}
}
Just some small code to get how the testing works.
In my HomeController I've got this code inside the Index():
public ActionResult Index()
{
ViewBag.Message = "Announcements";
NewsRepository n_rep = new NewsRepository();
var model = i_rep.GetNews();
return View(model);
}
I am completely new to testing so all explanations would be great.
Thanks.
Your controller is impossible to be unit tested in isolation because it is strongly coupled with your repository on the following line:
NewsRepository n_rep = new NewsRepository();
You have simply hardcoded a specific implementation of the repository and in your unit test you cannot mock it. In order to do this properly you should start by defining an abstraction over this repository:
public interface INewsRepository
{
IEnumerable<NewsItem> GetNews();
}
and then have your specific repository implement this interface:
public class NewsRepository : INewsRepository
{
...
}
Ok now that we have an abstraction let's weaken the coupling between your data access and controller logic by using this abstraction:
public class NewsController: Controller
{
private readonly INewsRepository repository;
public NewsController(INewsRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
ViewBag.Message = "Announcements";
var model = this.repository.GetNews();
return View(model);
}
}
Alright, now you have a controller that is no longer tightly coupled with some specific implementation. You could pickup your favorite mock framework and write a unit test. For example with NSubstitute here's how the unit test for the Index action might look like:
[TestMethod]
public void Index_Action_Fetches_Model_From_Repo()
{
// arrange
var repo = Substitute.For<INewsRepository>();
IEnumerable<NewsItem> expectedNews = new[] { new NewsItem() };
repo.GetNews().Returns(expectedNews);
var sut = new NewsController(repo);
// act
var actual = sut.Index();
// assert
Assert.IsInstanceOfType(actual, typeof(ViewResult));
var viewResult = actual as ViewResult;
Assert.AreEqual(expectedNews, viewResult.Model);
}
And that's pretty much it. Your controller is now easily unit testable in isolation. You don't need to be setting up databases or whatever. That's not the point to test the controller logic.
I'm looking into the possibilities to do TDD with TypeScript.
If I write my tests in TypeScript, is it possible to make the import statements return mocks for my class under test?
Or is the only feasible approach to write the tests in pure javascript and deal with injecting AMDs myself?
I have developed an IoC container called InversifyJS with advanced dependency injection features like contextual bindings.
You need to follow 3 basic steps to use it:
1. Add annotations
The annotation API is based on Angular 2.0:
import { injectable, inject } from "inversify";
#injectable()
class Katana implements IKatana {
public hit() {
return "cut!";
}
}
#injectable()
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
}
#injectable()
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(
#inject("IKatana") katana: IKatana,
#inject("IShuriken") shuriken: IShuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
2. Declare bindings
The binding API is based on Ninject:
import { Kernel } from "inversify";
import { Ninja } from "./entities/ninja";
import { Katana } from "./entities/katana";
import { Shuriken} from "./entities/shuriken";
var kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken);
export default kernel;
3. Resolve dependencies
The resolution API is based on Ninject:
import kernel = from "./inversify.config";
var ninja = kernel.get<INinja>("INinja");
expect(ninja.fight()).eql("cut!"); // true
expect(ninja.sneak()).eql("hit!"); // true
The latest release (2.0.0) supports many use cases:
Kernel modules
Kernel middleware
Use classes, string literals or Symbols as dependency identifiers
Injection of constant values
Injection of class constructors
Injection of factories
Auto factory
Injection of providers (async factory)
Activation handlers (used to inject proxies)
Multi injections
Tagged bindings
Custom tag decorators
Named bindings
Contextual bindings
Friendly exceptions (e.g. Circular dependencies)
You can learn more about it at https://github.com/inversify/InversifyJS
I use infuse.js for Dependency Injection in TypeScript.
Reference the d.ts
/// <reference path="definition/infusejs/infusejs.d.ts"/>
Initialize your injector at startup
this.injector = new infuse.Injector();
Map Dependencies
this.injector.mapClass( 'TodoController', TodoController );
this.injector.mapClass( 'TodoView', TodoView );
this.injector.mapClass( 'TodoModel', TodoModel, true ); // 'true' Map as singleton
Inject Dependencies
export class TodoController
{
static inject = ['TodoView', 'TodoModel'];
constructor( todoView:TodoView, todoModel:TodoModel )
{
}
}
It's string based as opposed to being type based (as reflection isn't yet possible in TypeScript). Despite that, it works very well in my applications.
Try this Dependency Injector (Typejector)
GitHub Typejector
With new TypeScript 1.5 it is possible using annotation way
For example
#injection
class SingletonClass {
public cat: string = "Kitty";
public dog: string = "Hot";
public say() {
alert(`${this.cat}-Cat and ${this.dog}-Dog`);
}
}
#injection
class SimpleClass {
public say(something: string) {
alert(`You said ${something}?`);
}
}
#resolve
class NeedInjectionsClass {
#inject(SingletonClass)
public helper: SingletonClass;
#inject(SimpleClass)
public simpleHelper: SimpleClass;
constructor() {
this.helper.say();
this.simpleHelper.say("wow");
}
}
class ChildClass extends NeedInjectionsClass {
}
var needInjection = new ChildClass();
For question case:
some property should realise pseudo Interface (or abstract class) like in next example.
class InterfaceClass {
public cat: string;
public dog: string;
public say() {
}
}
#injection(true, InterfaceClass)
class SingletonClass extends InterfaceClass {
public cat: string = "Kitty";
public dog: string = "Hot";
public say() {
alert(`${this.cat}-Cat and ${this.dog}-Dog`);
}
}
#injection(true, InterfaceClass)
class MockInterfaceClass extends InterfaceClass {
public cat: string = "Kitty";
public dog: string = "Hot";
public say() {
alert(`Mock-${this.cat}-Cat and Mock-${this.dog}-Dog`);
}
}
#injection
class SimpleClass {
public say(something: string) {
alert(`You said ${something}?`);
}
}
#resolve
class NeedInjectionsClass {
#inject(InterfaceClass)
public helper: InterfaceClass;
#inject(SimpleClass)
public simpleHelper: SimpleClass;
constructor() {
this.helper.say();
this.simpleHelper.say("wow");
}
}
class ChildClass extends NeedInjectionsClass {
}
var needInjection = new ChildClass();
Note: Mock injection should define after source code, because it mast redefine class-creator for interface
For people who use Angular2 I have developed Fluency Injection https://www.npmjs.com/package/fluency-injection. The documentation is quite complete and it mimics the behaviour of Angular2's DI.
Feedback is much appreciated and I hope it helps you :)
You can use the solution:
Lightweight dependency injection container for JavaScript/TypeScript
import {autoInjectable, container} from "tsyringe";
class MyService {
move(){
console.log('myService move 123', );
}
}
class MyServiceMock {
move(){
console.log('mock myService move 777', );
}
}
#autoInjectable()
export class ClassA {
constructor(public service?: MyService) {
}
move(){
this.service?.move();
}
}
container.register(MyService, {
useClass: MyServiceMock
});
new ClassA().move();
output:
mock myService move 777
I've been developing a DI solution called Pigly. An example given the original question regarding injecting and testing (admittedly not automatic-mock generation - although you could try ts-auto-mock as I've done here):
Given:
interface IDb {
set(key: string, value: string);
}
interface IApi {
setName(name: string);
}
class Api implements IApi {
constructor(private db: IDb) {}
setName(name: string){
this.db.set("name", name);
}
}
We can bind the types with,
import { Kernel, toSelf, to, toConst } from 'pigly';
import * as sinon from 'sinon';
let spy = sinon.spy();
let kernel = new Kernel();
kernel.bind(toSelf(Api));
kernel.bind<IApi>(to<Api>());
kernel.bind<IDb>(toConst({ set: spy }));
then resolve and test with:
let api = kernel.get<IApi>();
api.setName("John");
console.log(spy.calledWith("name", "John"));
execution/compilation of this example requires a typescript transformer - to compile the interface-symbols and constructor provider into plain javascript. There are a few ways to do this. The ts-node + ttypescript approach is to have a tsconfig.json:
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"moduleResolution": "node",
"plugins": [{
"transform": "#pigly/transformer"
}]
}
}
and execute with
ts-node --compiler ttypescript example-mock.ts
Pigly has the distinction of not requiring any changes to your (or third-party) classes, at the expense of either the use of a typescript transformer, or more verbose binding if (you don't want to use the transformer). Its still experimental, but I think it shows promise.
TypeScript works well with AMD loaders like requirejs. If confgured properly, TypeScript will output fully AMD compliant javascript.
In a testing situation, you could configure requirejs to inject testable modules.
You can give this a shot: https://www.npmjs.com/package/easy-injectionjs. It is a generic use dependency injection package.
#EasySingleton creates a single instance of the dependency through the entire application. It is ideal for a service of some sort.
#EasyPrototype creates as many instances of the dependency as needed. It is ideal for changeable dependencies.
#EasyFactory is primarily used for inheritance:
You can do anything using this package:
Simple usage (Coming from the readme):
import { Easy, EasyFactory, EasyPrototype, EasySingleton } from 'easy-injectionjs';
#EasyFactory()
abstract class Person {
abstract getName();
abstract setName(v: string);
}
// #EasyObservable()
#EasySingleton()
class Somebody extends Person{
// #Easy()
constructor (private name: string) {
super()
this.name = 'Sal';
}
public getName() {
return this.name;
}
public setName(v: string) {
this.name = v;
}
}
#EasyPrototype()
class Nobody extends Person{
#Easy()
somebody: Person;
constructor () {
super()
}
public getName() {
return this.somebody.getName();
}
public setName(v: string) {
this.somebody.setName(v);
}
}
#EasyPrototype()
class Data {
#Easy()
somebody: Person;
name: string;
change(v: string) {
this.somebody.setName(v);
}
getName(): string {
return this.somebody.getName();
}
}
let n = new Nobody();
console.log(n.getName()) // Prints Sal
n.setName('awesome');
console.log(n.getName()) // Prints awesome
let d = new Data()
console.log(d.getName()) // Prints awesome
d.change('Gelba')
console.log(n.getName()) // Prints Gelba
d.change('kaa')
console.log(n.getName()) // Prints Kaa
Even if you want to inject node modules you can do this:
import * as IExpress from 'express';
import { Easy, EasySingleton } from 'easy-injectionjs';
#EasySingleton()
class Express extends IExpress {}
#EasySingleton()
export class App {
#Easy()
private _express: Express;
}
let app = new App();
console.log(app)
Of course, the usage of the express server isn't for console logging. It is just for testing :D.
Hope that helps :D
Dime is a very simple dependency injection library. It's very early into development, though, so it probably has some bugs. There is more information on the wiki page.
Example usage:
import { ItemsService } from './items-service'; // ItemsService is an interface
import { Inject } from '#coined/dime';
class ItemsWidget {
#Inject()
private itemsService: ItemsService;
render() {
this.itemsService.getItems().subscribe(items => {
// ...
});
}
}
// Setup
const appPackage = new Package("App", {
token: "itemsService",
provideClass: AmazonItemsService // AmazonItemsService implements ItemsService
});
Dime.mountPackages(appPackage);
// Display the widget
const widget = new ItemsWidget();
widget.render();
I work on AutoFixtureTS that is inspired by AutoFixture. AutoFixtureTS makes it easier for TypeScript developers to do Test-Driven Development by automating non-relevant Test Fixture Setup, allowing the Test Developer to focus on the essentials of each test case.
http://ronniehegelund.github.io/AutoFixtureTS/
Its still just prototype code, but check it out :-)
/ronnie
I'm getting into writing unit testing and have implemented a nice repository pattern/moq to allow me to test my functions without using "real" data. So far so good.. However..
In my repository interface for "Posts" IPostRepository I have a function:
Post getPostByID(int id);
I want to be able to test this from my Test class but cannot work out how.
So far I am using this pattern for my tests:
[SetUp]
public void Setup()
{
mock = new Mock<IPostRepository>();
}
[Test]
public void someTest()
{
populate(10); //This populates the mock with 10 fake entries
//do test here
}
In my function "someTest" I want to be able to call/test the function GetPostById. I can find the function with mock.object.getpostbyid but the "object" is null.
Any help would be appreciated :)
iPostRepository:
public interface IPostRepository
{
IQueryable<Post> Posts {get;}
void SavePost(Post post);
Post getPostByID(int id);
}
I'm not sure what unit testing framework you are using, but I am using NUnit. I'm not a unit testing pro, but I know enough to get me started and to get results.
I normally have a service layer, and this will call my post repository:
public class PostService
{
private readonly IPostRepository postRepository;
public PostService(IPostRepository postRepository)
{
if (postRepository== null)
{
throw new ArgumentNullException("postRepository cannot be null.", "postRepository");
}
this.postRepository = postRepository;
}
public Post GetPostById(int id)
{
return postRepository.GetPostById(id);
}
}
Your unit tests could look like this:
[TestFixture]
public class PostServiceTests
{
private PostService sut;
private Mock<IPostRepository> postRepositoryMock;
private Post post;
[SetUp]
public void Setup()
{
postRepositoryMock = new Mock<IPostRepository>();
sut = new PostService(postRepositoryMock.Object);
post = new Post
{
Id = 5
};
}
[Test]
public void GetPostById_should_call_repository_to_get_a_post_by_id()
{
int id = 5;
postRepositoryMock
.Setup(x => x.GetPostById(id))
.Returns(post).Verifiable();
// Act
Post result = sut.GetPostById(id);
// Assert
Assert.AreEqual(post, result);
postRepositoryMock.Verify();
}
}
I hope this helps.
If you want your mock object to return a result (not null), you need to set it up:
mock.Setup( m => m.GetPostByID( 5 ) ).Returns( new Post() );
What you return exactly is up to you of course.
Update:
If you need to use the method parameters you can also setup a CallBack. For example:
mock.Setup( m => m.GetPostByID( It.IsAny<int>() ) )
.Callback( id => return new Post{ Id = id; } );
This may make your setup code much easier since you don't need to prime the mock with data.
If you want to test the real implementation of GetPostById, do so via the real implementation of IPostRepository. Moq (and mocks in general) are only for situation where you don't want to use the real thing.
In other words prime your database with some posts, new up the real repository, call GetPostById and make assertions on the result. This is not strictly a unit test though, but an integration test because it includes the database.
How can I use LINQ if I have wrapped my Entity Framework data context with a Repository class?
I want to do something like:
class A
{
public IRepositiry<T> GetRepository<T>()
{
DbContextAdapter adapter = new DbContextAdapter(ctx);
return new Repository<T>(adapter);
}
}
class B
{
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
// Do some linq queries here, don't know how.
rep.[get Linqu] (from ...);
}
}
To keep your repository LINQ friendly you need to have some methods or properties on it that return IQueryable<T> or IEnumerable<T>
So in class Repository<T> you would have a method like this:
public class Repository<T>
{
DbContextAdapter ctx;
// other methods omitted
IEnumerable<Houses> GetHouses()
{
return ctx.Houses
}
}
Then in DoSomething you could do this:
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
var q = from house in rep.GetHouses()
where house.Color = "Purple"
select house;
foreach(var h in q)
{
house.SetOnFire();
}
}
The standard query operators allow queries to be applied to any
IEnumerable-based information source. - MSDN
As long as you write methods that return IEnumerable Collections you will be compatible with LINQ.
at the risk of been completely lazy, what you want to implement is known as the repository pattern, check out Huyrya as its a good article.
Also it's possible to extend the entity classes, so they return instances or lists of themselves (singleton pattern). Aka:
public partial class FOO : FOO
{
public IEnumerable<Foo> GetFooList()
{
using (var context = new FooEntities())
{
return // YOU CODE TO GET LIST OF FOO
}
}
}
Or something like that (code syntax is not right but should give you the general idea). If your entity classes are going to implement similar methods, abstract them into interface contract and get your partial entity classes to implement that interface.