samedi 31 janvier 2015

rails weird test faliures

I am testing rails using the default testing suite I have a personal model and address associated model. I have first written the personal model then all its test were passing after implementing address model some of the personal test are failing and I have no clue



personal.rb


class Personal < ActiveRecord::Base
belongs_to :applicant
has_many :addresses
validates_associated :addresses

validates :first_name, presence: true, length: { maximum: 24 }
validates :last_name, presence: true, length: { maximum: 24 }
validates :middle_name, length: { maximum: 24 }
validates :fathers_name, presence: true, length: { in: 2..50 }
validates :mothers_name, presence: true, length: { in: 2..50 }
validates :date_of_birth, presence: true
validates :gender, presence: true, inclusion: { in: %w(M F O) }
validates :religion, presence: true, length: { in: 2..20 }
validates :caste, presence: true, inclusion: { in: %w(GEN SC ST OBC_A OBC_B) }
validates :phone, format: { with: /((\+*)((0[ -]+)*|(91 )*)(\d{12}+|\d{10}+))|\d{5}([- ]*)\d{6}|\d{2}([- ]*)\d{7}/ },
length: { maximum: 16 }

validates :mobile, presence: true, format: { with: /(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}/ },
length: { maximum: 14 }

accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['line1'].blank? }
validate :personal_has_address

private
def personal_has_address
if self.addresses.size == 0
errors.add(:addresses, "There are no address")
end
end

end


and its test as in personal_test.rb



require 'test_helper'

class PersonalTest < ActiveSupport::TestCase
def setup
@personal = personals(:three)
@personal.applicant = applicants(:sourav)
@address = addresses(:three)
@address.personal = @personal
end

test "should be valid" do
assert @personal.valid?
end

test "first name should be present" do
@personal.first_name = " "
assert_not @personal.valid?
end

test "first name should not be too long" do
@personal.first_name = "a" * 25
assert_not @personal.valid?
end

test "last name should be present" do
@personal.last_name = " "
assert_not @personal.valid?
end

test "last name should not be too long" do
@personal.last_name = "a" * 25
assert_not @personal.valid?
end

test "middle name may not be present" do
@personal.middle_name = " "
assert @personal.valid?
end

test "middle name should not be too long" do
@personal.middle_name = "a" * 25
assert_not @personal.valid?
end

test "fathers name may not be present" do
@personal.fathers_name = " "
assert_not @personal.valid?
end

test "fathers name should not be too long" do
@personal.fathers_name = "a" * 51
assert_not @personal.valid?
end

test "fathers name should not be too small" do
@personal.fathers_name = "a"
assert_not @personal.valid?
end

test "mothers name may not be present" do
@personal.mothers_name = " "
assert_not @personal.valid?
end

test "mothers name should not be too long" do
@personal.mothers_name = "a" * 51
assert_not @personal.valid?
end

test "mothers name should not be too small" do
@personal.mothers_name = "a"
assert_not @personal.valid?
end

test "date of birth must be present" do
@personal.date_of_birth = " "
assert_not @personal.valid?
end

test "gender must be present" do
@personal.gender = " "
assert_not @personal.valid?
end

test "gender must be either Male Female or others" do
@personal.gender = "A"
assert_not @personal.valid?
end

test "gender validation should accept valid genders" do
genders = %w(M F O)
genders.each do |gender|
@personal.gender = gender
assert @personal.valid?, "#{gender} is valid gender"
end
end

test "gender validation should reject invalid genders" do
genders = %w(Random A B Male Female Others)
genders.each do |gender|
@personal.gender = gender
assert_not @personal.valid?, "#{gender} is invalid gender"
end
end

test "gender must not be too long" do
@personal.gender = "Ma"
assert_not @personal.valid?
end

test "religion must not be empty" do
@personal.religion = " "
assert_not @personal.valid?
end

test "religion should not be too long" do
@personal.religion = "a" * 21
assert_not @personal.valid?
end

test "religion should not be too short" do
@personal.religion = "a"
assert_not @personal.valid?
end

test "caste validation should reject invalid castes" do
castes = %w(Schedule tribe caste brahmin random Sc tS obc)
castes.each do |caste|
@personal.caste = caste
assert_not @personal.valid?, "#{caste} is invalid caste"
end
end

test "caste validation should accept valid castes" do
castes = %w(GEN SC ST OBC_A OBC_B)
castes.each do |caste|
@personal.caste = caste
assert @personal.valid?, "#{caste} is valid caste"
end
end

test "caste should be present" do
@personal.caste = " "
assert_not @personal.valid?
end

test "phone should not be too long" do
@personal.phone = "1" * 17
assert_not @personal.valid?
end

test "phone validation should accept valid phones" do
phones = ["9775876662", "0-9778545896", "919578965389", "03595-259506", "03598245785", "0 9754845789", "+91 9456211568", "03592 245902"]
phones.each do |phone|
@personal.phone = phone
assert @personal.valid?, "#{phone} is valid phone"
end
end

test "phone validation should reject invalid phones" do
phones = ["1", "033", "97758", "0-9+knv", "random", "0", "12345", "845789", "+91", "033 24028485abcdjj"]
phones.each do |phone|
@personal.phone = phone
assert_not @personal.valid?, "#{phone} is invalid phone"
end
end

test "mobile no should nit be too long" do
@personal.mobile = "1" * 15
assert_not @personal.valid?
end

test "mobile validation should accept valid mobiles" do
mobiles = ["9775876662", "919578965389", "+91-9456211568", ]
mobiles.each do |mobile|
@personal.mobile = mobile
assert @personal.valid?, "#{mobile} is valid mobile"
end
end

test "mobile validation should reject invalid mobiles" do
mobiles = ["1", "033", "97758", "0-9+knv", "random", "0", "12345", "845789", "+91", "033 24028485abcdjj"]
mobiles.each do |mobile|
@personal.mobile = mobile
assert_not @personal.valid?, "#{mobile} is invalid mobile"
end
end

end


and address.rb



class Address < ActiveRecord::Base
belongs_to :personal, dependent: :destroy

validates :line1, presence: true, length: { in: 5..100 }
validates :line2, length: { maximum: 100 }
validates :city_village, presence: true, length: { maximum: 49}
validates :state, presence: true, length: { maximum: 29}
validates :country, presence: true, length: { maximum: 29}
validates :pin, presence: true, numericality: { only_integer: true }
end


Test results



Run options: --seed 12821

# Running:

...FFF..F.......FF...........................

Finished in 0.420629s, 106.9826 runs/s, 180.6817 assertions/s.

1) Failure:
PersonalTest#test_middle_name_may_not_be_present [/home/smoitra/projects/admission/test/models/personal_test.rb:37]:
Failed assertion, no message given.


2) Failure:
PersonalTest#test_caste_validation_should_accept_valid_castes [/home/smoitra/projects/admission/test/models/personal_test.rb:138]:
GEN is valid caste


3) Failure:
PersonalTest#test_phone_validation_should_accept_valid_phones [/home/smoitra/projects/admission/test/models/personal_test.rb:156]:
9775876662 is valid phone


4) Failure:
PersonalTest#test_mobile_validation_should_accept_valid_mobiles [/home/smoitra/projects/admission/test/models/personal_test.rb:177]:
9775876662 is valid mobile


5) Failure:
PersonalTest#test_should_be_valid [/home/smoitra/projects/admission/test/models/personal_test.rb:12]:
Failed assertion, no message given.


6) Failure:
PersonalTest#test_gender_validation_should_accept_valid_genders [/home/smoitra/projects/admission/test/models/personal_test.rb:94]:
M is valid gender

45 runs, 76 assertions, 6 failures, 0 errors, 0 skips
45 tests
76 assertions, 6 failures, 0 errors

106.86 tests/s, 180.47 assertions/s

Finished in 0.4211 seconds

How to use Redis in unit testing?

Suppose I have a method in my controller class that updates the score of a key,value pair in a Redis database. I want to write a unit test to check if the score is not null and is incremented by 1. I just want to see how unit testing works with Redis and how you extract the score from a particular key, value pair and check its validity.


Controller Class //When user refreshes api/do/v1/togglelike/{id}", the score is updated in redis for that user and is incremented by 1;



[HttpGet]
[Route("api/do/v1/togglelike/{id}")]
public IHttpActionResult ToggleLike(String id)
{
var currentUser = "mike";


var likeSet = redis1.SortedSetRangeByScore("likes:" + id);
var likeStatus = redis1.SortedSetScore("likes:" + id, currentUser);

//Current user has not yet liked the profile
if (likeStatus == null)
{
redis1.SortedSetAdd("likes:" + id, currentUser, 1);
return Ok("Like Added");

}
/*redis1.SortedSetAdd("likes:" + id, currentUser, 1);
return Ok("Like Added");*/
else
{
double counter = redis1.SortedSetIncrement("likes:" + id, currentUser, 1);
redis1.SortedSetAdd("likes:" + id, currentUser, counter);
return Ok("Like Added");
/*redis1.SortedSetRemove("likes:" + id, currentUser);
return Ok("Like Removed");*/
}
}


Test Class: I want to get the score from the key,value pair and check that it is equal to a valid number;



namespace VideoControllerTest
{
[TestClass]
public class VideoControllerTest
{
IDatabase redis1;

public VideoControllerTest()
{
redis1 = RedisFactory.Connection.GetDatabase();
}

[TestMethod]
public void VideoController_Adview()
{
//Arrange
VideoController controller = new VideoController();
//Act
IHttpActionResult actionResult = controller.ToggleLike("video123");

//Assert; Check to see the counter is incremented by 1 and is not null;

}
}
}

Unit testing Symfony service's internal behavior

I have a Symfony service that takes some input, generates a file and uploads that file via FTP. I'd like to test that the file format is correctly generated, however, this is never returned by the service for me to test in PHPUnit. The service's only public API is send(). How can I use PHPUnit to test the internal behavior of my service (the file format generated)?


Symfony Unit Test Form Extension Mock

Before updating my code via composer my forms unit test was working. It is now failing on the extension mock. Heres the error:



Argument 1 passed to Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension::__construct() must be an instance of Symfony\Component\Validator\ValidatorInterface, instance of Mock_ValidatorInterface_14b95ba0 given


Heres my composer required section:



"require": {
"php": ">=5.3.3",
"symfony/symfony": "~2.3",
"doctrine/orm": "~2.2,>=2.2.3",
"doctrine/doctrine-bundle": "~1.2",
"twig/extensions": "~1.0",
"symfony/assetic-bundle": "~2.3",
"symfony/swiftmailer-bundle": "~2.3",
"symfony/monolog-bundle": "~2.3",
"symfony/monolog-bridge": "~2.4",
"sensio/distribution-bundle": "~2.3",
"sensio/framework-extra-bundle": "~2.3"
}


Heres the validation mock in the unit test setup method:



use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Form\Extension\Core\CoreExtension;

class TestedTypeTest extends TypeTestCase
{

protected function setUp()
{
parent::setUp();

$validator = $this->getMock('\Symfony\Component\Validator\Validator\ValidatorInterface');
$validator->method('validate')->will($this->returnValue(new ConstraintViolationList()));
$formTypeExtension = new FormTypeValidatorExtension($validator);
$coreExtension = new CoreExtension();

$this->factory = Forms::createFormFactoryBuilder()
->addExtensions($this->getExtensions())
->addExtension($coreExtension)
->addTypeExtension($formTypeExtension)
->getFormFactory();
}


Does anyone know what might be wrong with the mock? Any advice is greatly appreciated.


Working with SpriteKit's physics engine - units explanation/conversions

The hardest thing about SpriteKit is figuring it's unexplained units. Apple does say "all units are in SI units" but makes no reference about how you relate this to points.


Can't debug test using breakpoint in Visual Studio 2013

I'm trying to debug a failing unit test by putting a breakpoint at the beginning of the test method and choosing Debug Selected Tests in the Test Explorer. However, the test always runs (and fails) without hitting the breakpoint.


I've tried:



  • Cleaning and rebuilding the project

  • Restarting Visual Studio


This seems like a pretty basic case - I'm not attaching to a separate process, or doing anything fancy. Just a basic unit test inside VS2013. What else can I try to get the debugger to work correctly?


Integration tests and test coverage

For I project I have made a wcf service library. It can be hosted in IIS and in a self-hosted service.


For all external systems, I have provided Mock implementations which give some generic data, so such the service keeps running and doing work. It is a classic automaton / finite-state machine.


While bootstrapping, all data sources are connected. In testing mode, the mock implementations are connected. So when I run tests, the service library is "started" from a self-hosted service, not IIS and the the state machine keeps running.


Is there any way to get some kind of "test coverage" from such a run.


I would really appreciate if I could tell which code paths are hit by the example data I provide. And provide more testdata to get a higher coverage.


how to setup a unittest for a web-project

I have problems to properly configure my first unittest in the DartEditor.


I wrote a web-app with dart that is located in the web-folder. Now i added a test-folder parallel to web with a file called test.dart: library dartingflame_test;



import 'dart:math';
import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';
import 'package:mockito/mockito.dart';
import '../web/dartingflame.dart';

void main() {
useHtmlConfiguration();

test("verify robot's direction after move", verifyRobotDirectionAfterMove);
}

void verifyRobotDirectionAfterMove() {...}


Unfortunatly i now have problems to run this test file.



  • Run with Dartium leads to the message: Unable to locate associated html file

  • Run leads to: Observatory listening on http://127.0.0.1:49919 The built-in library 'dart:html' is not available on the stand-alone VM. 'package:unittest/html_config.dart': error: line 10 pos 1: library handler failed import 'dart:html';


Using useVMConfiguration() instead of useHtmlConfiguration() doesn't help. The test execution still complaints about the import 'dart:html';-line in the library under test.


I couldn't find a solution in the "Unit Testing with Dart"-article.


Data drive intergration on CI and buid server

I am writing intergartion test which will take certain input and get output and will verify them . Now the data will keep on changing on each enviornment like dev , CI and other env.


Now wanted to know what are the best practices to write these kind of test cases and also how the data should be maintaned.


Any live exmaple or pseudo code will also help


To test if a model was saved before passed on to task queue?

In the following method the correct behaviour would to to save the news model before passing its id to the asynchronous Task queue for further processing. Otherwise the task queue has the older version.


As you can see I have made a mistake and am saving the model after sending its id to the task queue.



def save_scraped_body_into_model(url_string):
news = ndb.Key(urlsafe=url_string).get()
...
news.body = result
news.stage = 1
taskqueue.Task(url='/api/v1.0/worker/bbc-stage-2', headers=header,
payload=json.dumps({'news_url_string': news.key.urlsafe()})).add(queue_name='newstasks')
news.put()


Do I possibly test for that? My test below passes as long as the model was saved. But thats wrong, the order matters, and this test doesn't capture it !!! Is there a way to achieve this with mock?



def test_news_instance_saved_before_next_stage(self, get_head):
BBCSpider.save_scraped_body_into_model(self.news.key.urlsafe())
context = ndb.get_context()
context.clear_cache()
news = ndb.Key(urlsafe=self.news.key.urlsafe()).get()
self.assertEqual(news.stage, 1)

unit test for service with a promise

I have a service that i wrote for a project i am currently working on and i am trying to write a unit test for it. Below is the code for the service



angular.module('services').factory('Authorization', ['$q', 'Refs', function($q, Refs) {

function isAuthorized() {
var deferred = $q.defer();

var authData = Refs.rootRef.getAuth();
var adminRef;

if(authData.google) {
adminRef = Refs.rootRef.child('admins').child(authData.uid);
} else {
adminRef = Refs.rootRef.child('admins').child(authData.auth.uid);
}

adminRef.on('value', function(adminSnap) {
deferred.resolve(adminSnap.val());
});
return deferred.promise;
}

return {
isAuthorized: isAuthorized
};
}]);


I have written a unit test for it but anytime i run the test i get this error message ' Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.'


Below is the code for the unit test i wrote for the service:



'use strict';

describe('Authorization Service', function() {

var Refs, $q, Authorization, authData, scope, deferred;

beforeEach(angular.mock.module('Sidetime'));

beforeEach(inject(function(_Refs_, $rootScope, _$q_, _Authorization_) {
Refs = _Refs_;
$q = _$q_;
Authorization = _Authorization_;
}));

iit('return admin object', function(done) {
var result;

Authorization.isAuthorized = function() {
deferred = $q.defer();
authData = {google: 'uid:112222'};

if(authData.google) {
deferred.resolve(authData);
}

return deferred.promise;
};

Authorization.isAuthorized().then(function(result) {
console.log('result', result);
expect(result).toEqual(authData);
//done();
});
});
});


I am not sure I am writing the unit test properly. I will appreciate if someone could show be a better way of writing the unit test for this service. Thanks for your anticipated assistance.


Imitate bundle unit testing with symfony2

I try to write tests for my app, but I dont know how in my tests I can imitate some bundle. For example I want to my function what work with any bundle you assign,for now I testing AcmeDemoBundle, but what if user what will be use my bundle delete AcmeDemoBundle ?


How to unit test view_func in urls?

I am using mock package to help out with writing unit tests. (even though I am not mocking in this particular example, but I could if it helps achieving my goal)


I have the following routing rule defined and would like to test it.



app.add_url_rule('/api/v1.0/worker/bbc-stage-0', 'stage0', view_func=BBCStage0TaskView.as_view('bbc_stage0_taskview'))


The following test allows to see if the path is correct:



def test_url_to_view_stage0_exists(self):
self.assertEqual(api.app.url_map._rules_by_endpoint['stage0'][0].rule, '/api/v1.0/worker/bbc-stage-0')


But I haven't found a way to test if view_func is pointing to the right class. Is there a way to achieve this?


assertEqual not works when testing equals of command output

Here is what I output in my command:



$output->writeln("\033[37;42m Translations from " . $input->getArgument('bundle') . " imported successfully! \033[0m");


Here is what I get in command line with trim func to delete spaces:



trim($commandTester->getDisplay())
..string(69) " Translations from AcmeDemoBundle imported successfully! "


But when I run this:



$this->assertEquals(" Translations from AcmeDemoBundle imported successfully! ", trim($commandTester->getDisplay()));


I get:



Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-' Translations from AcmeDemoBundle imported successfully! '
+Binary String: ...


What I am doing wrong?


testing commands in Symfony2

I want to write the tests for my console command. But my knowledge of testing is pretty pure. So I have the command what get the file from bundle, and sets values of file into memcached. For memcached I wrote myself wrapper, and declare it as service. So I need to extend my test from KernelTestCase or \PHPUnit_Framework_TestCase. And I need to do all by hands(like create array, set it into memcached for simulate work of command) or I just need use Symfony\Component\Console\Tester\CommandTester; ? Can somebody help me? Thanks!


vendredi 30 janvier 2015

Swift function with a closure parameter seen as error type inside Unit Testing Module

I'm trying to write Unit tests for my Article Model. I have added the model as a test target.


I am able to access class functions without closure parameters in it but when I try to use a function with a closure, here's what Xcode's autocompletion gave


enter image description here


The full function prototype of 'fetchArticles' looks likes this:



class func fetchArticles(referringTile:Tile,completion:(articles:[Article])->(Void),
failure:(error:NSError)->(Void))


I've also tried declaring the function as 'public' but it didn't work.


AFNetworking 2.0: Subclassing AFHTTPSessionManager for TDD causing error in AFURLRequestSerialization init

I've subclassed AFHTTPSessionManager in order to make a mock out of it to use while testing. However, I keep running into a BAD_ACCESS error in AFURLRequestSerialization's init method - only with the mock. Here's the setup:


Testing class:



@interface PLBookCommunicatorTests : XCTestCase
@end

@implementation PLBookCommunicatorTests
{
MockAFHTTPSessionManager *httpSessionManager;
HKCommunicator *communicator;
}

- (void)setUp
{
[super setUp];

httpSessionManager = [[MockAFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://base.url"]];

communicator = [[HKCommunicator alloc] initWithHttpSessionManager:httpSessionManager];
}


MockAFHTTPSessionMannager.h



#import "AFHTTPSessionManager.h"

@interface MockAFHTTPSessionManager : AFHTTPSessionManager

@property (nonatomic, assign) BOOL successful;

@end


MockAFHTTPSessionManager.m



import <AFNetworking.h>
#import "MockAFHTTPSessionManager.h"

@implementation MockAFHTTPSessionManager

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
if(self.successful)
{
success(nil, nil);
}
else
{
failure(nil, nil);
}

return nil;
}

@end


I run into an error in this portion of AFURLRequestSerialization's init method:



self.mutableObservedChangedKeyPaths = [NSMutableSet set];
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
}
}


Specifically, at the [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; line. It catches on the very first run of that for loop


I'm not understanding why that line catches only in my mock. Is there something I'm missing while subclassing AFHTTPSessionManager? Perhaps something to do with the addObserver method?


Swift - Getting around build errors in test-driven development?

I'm starting to learn how to do test-driven development, and I'm working with Swift. I'm suppose to have a test which should fail then write the code needed to get it to pass. From my understanding the test should successfully run, just fail. However, in Swift, when I try to write a test that, say, checks the value of a object's specific attribute, if that class doesn't yet have such an attribute (because I'm suppose to write the test first before I create it for that class) I don't get a failing test, but instead a build error when attempting to build and run the test. The error is that the test is trying to access an attribute that doesn't exist for the given object. Am I going about this the wrong way? Or are these test build breaking errors suppose to be what I get when doing TDD in Swift? Thanks!


How can we tell grails mongodb unit test to use a db?

I setup a db in mongodb called spotlight. To connect to that database, I use the following environment setup in DataSource.groovy:



grails {
mongo {
host = "localhost"
port = 27017

}
}


environments {
development { // MongoDB instance running without --auth flag.
grails {
mongo {
databaseName = "spotlight"
}
}
}
test {
grails { // MongoDB instance running without --auth flag.
mongo {
databaseName = "spotlight"
}
}
}

}


This is my unit test class:



@TestMixin(MongoDbTestMixin)
class BiographySpec extends Specification {

def setup() {
}

def cleanup() {
}

void "given a bio then find() returns that bio object"() {


given:
mongoDomain([Biography])
Biography bio = new Biography()

def nameOf1stImage = "firstImage.png"
def nameOf2ndImage = "secondImage.png"
def nameInBio = "star"
def descriptionOfBio = "a description"
def id = 0;

bio.firstImage = nameOf1stImage
bio.secondImage = nameOf2ndImage
bio.name = nameInBio
bio.description = descriptionOfBio
bio.images = [nameOf1stImage,nameOf2ndImage]

when:
bio.save(flush:true);
id = bio.id

then:
Biography bioFromDb = bio.get(id)
bioFromDb.firstImage == nameOf1stImage
bioFromDb.secondImage == nameOf2ndImage
bioFromDb.name == nameInBio
bioFromDb.description == descriptionOfBio
}


}


I ran grails test-app, and grails created a biography document in test db, not spotlight db. Is there anything wrong with the way I configure environments setttings in DataSource.groovy ?


Thank you


How do you mock a JavaFX toolkit initialization?

[preamble: apologies, there is a lot of code here, and some of it may not be relevant to this question while some code which is necessary to understand the problem may be missing; please comment, and I will edit the question accordingly.]


Environment: Ubuntu 14.10 x86_64; Oracle JDK 1.8u25. Unit testing library is TestNG, version 6.8.13; Mockito is version 1.10.17.


In my GUI application, what JavaFX calls a "controller" is pretty passive, in the sense that the only thing that this "controller" (which I call a "display") really does is send events.


Now, when an event is received which requires a GUI update, it is another class, which I call a view, which is responsible for updating the GUI. In short:


display -> presenter -> view -> display


I have unit tests for two of these:



  • display -> presenter;

  • presenter -> view.


So, I am pretty much covered on this front (with the advantage that I can change the display, which is why I'm doing it that way).


But now I try and test the "view -> display" part; and I am SOL.


As an illustration, here is the view class:



@NonFinalForTesting
public class JavafxTreeTabView
extends JavafxView<TreeTabPresenter, TreeTabDisplay>
implements TreeTabView
{
private final BackgroundTaskRunner taskRunner;

public JavafxTreeTabView(final BackgroundTaskRunner taskRunner)
throws IOException
{
super("/tabs/treeTab.fxml");
this.taskRunner = taskRunner;
}

JavafxTreeTabView(final BackgroundTaskRunner taskRunner,
final Node node, final TreeTabDisplay display)
{
super(node, display);
this.taskRunner = taskRunner;
}


@Override
public void loadTree(final ParseNode rootNode)
{
taskRunner.compute(() -> buildTree(rootNode), value -> {
display.parseTree.setRoot(value);
display.treeExpand.setDisable(false);
});
}

@Override
public void loadText(final InputBuffer buffer)
{
final String text = buffer.extract(0, buffer.length());
display.inputText.getChildren().setAll(new Text(text));
}

@VisibleForTesting
TreeItem<ParseNode> buildTree(final ParseNode root)
{
return buildTree(root, false);
}

private TreeItem<ParseNode> buildTree(final ParseNode root,
final boolean expanded)
{
final TreeItem<ParseNode> ret = new TreeItem<>(root);

addChildren(ret, root, expanded);

return ret;
}

private void addChildren(final TreeItem<ParseNode> item,
final ParseNode parent, final boolean expanded)
{
TreeItem<ParseNode> childItem;
final List<TreeItem<ParseNode>> childrenItems
= FXCollections.observableArrayList();

for (final ParseNode node: parent.getChildren()) {
childItem = new TreeItem<>(node);
addChildren(childItem, node, expanded);
childrenItems.add(childItem);
}

item.getChildren().setAll(childrenItems);
item.setExpanded(expanded);
}
}


The matching display class is this:



public class TreeTabDisplay
extends JavafxDisplay<TreeTabPresenter>
{
@FXML
protected Button treeExpand;

@FXML
protected TreeView<ParseNode> parseTree;

@FXML
protected TextFlow inputText;

@Override
public void init()
{
parseTree.setCellFactory(param -> new ParseNodeCell(presenter));
}

@FXML
void expandParseTreeEvent(final Event event)
{
}

private static final class ParseNodeCell
extends TreeCell<ParseNode>
{
private ParseNodeCell(final TreeTabPresenter presenter)
{
setEditable(false);
selectedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(
final ObservableValue<? extends Boolean> observable,
final Boolean oldValue, final Boolean newValue)
{
if (!newValue)
return;
final ParseNode node = getItem();
if (node != null)
presenter.parseNodeShowEvent(node);
}
});
}

@Override
protected void updateItem(final ParseNode item, final boolean empty)
{
super.updateItem(item, empty);
setText(empty ? null : String.format("%s (%s)", item.getRuleName(),
item.isSuccess() ? "SUCCESS" : "FAILURE"));
}
}
}


and here is my test file:



public final class JavafxTreeTabViewTest
{
private final Node node = mock(Node.class);
private final BackgroundTaskRunner taskRunner = new BackgroundTaskRunner(
MoreExecutors.newDirectExecutorService(), Runnable::run
);
private JavafxTreeTabView view;
private TreeTabDisplay display;

@BeforeMethod
public void init()
throws IOException
{
display = new TreeTabDisplay();
view = spy(new JavafxTreeTabView(taskRunner, node, display));
}

@Test
public void loadTreeTest()
{
final ParseNode rootNode = mock(ParseNode.class);
final TreeItem<ParseNode> item = mock(TreeItem.class);

doReturn(item).when(view).buildTree(same(rootNode));

display.parseTree = mock(TreeView.class);
display.treeExpand = mock(Button.class);

view.loadTree(rootNode);


verify(display.parseTree).setRoot(same(item));
verify(display.treeExpand).setDisable(false);
}
}


I expected it to work... Except that it doesn't. However "far apart" I try to steer away from the platform code, even the test class above fails with this exception:



java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor5.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:14)
at org.mockito.internal.creation.cglib.ClassImposterizer.createProxy(ClassImposterizer.java:143)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:58)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.Mockito.mock(Mockito.java:1163)
at com.github.fge.grappa.debugger.csvtrace.tabs.JavafxTreeTabViewTest.loadTreeTest(JavafxTreeTabViewTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
at org.testng.SuiteRunner.run(SuiteRunner.java:254)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:270)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:265)
at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:540)
at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:502)
at javafx.scene.control.Control.<clinit>(Control.java:87)
... 44 more


So, in short, how do I prevent the exception above from happening? I'd have thought that mocking the widgets away would have been enough, but apparently not :/ It looks like I need to mock the whole "platform context" (for lack of a better word for it) but I have no idea how.


How to modify a text file's "Date modified" property without affecting the content using c++?

I was doing a unit testing on one of my method. One criteria for the method to select the file into the result vector is the file is updated from last few hours. However, to ensure there is a valid result whenever I run the test, I need to keep at least one of the file "up to date".


Any idea about how to approach this except trying to copy the file to a temp file and write it back to the original file?


Fitnesse API returning tables with rows out of order

First I want to say that I am very new to fitnesse, in fact I am just starting to kick the tires.


So I have a test page with the following content:


| eg.Division |


| numerator | denominator | quotient? |


| 10 | 2 | 5.0 |


| 12.6 | 3 | 4.2 |


| 22 | 7 | ~=3.14 |


| 9 | 3 | <5 |


| 11 | 2 | 4<_<6 |


| 100 | 4 | 33 |


However, when I call the API to get the data the rows come out of order so it is hard to see the columns.


Output:



{
tables: [
{
9: "3",
10: "2",
11: "2",
22: "7",
100: "4",
eg.Division: { },
12.6: "3",
numerator: "denominator"
}
]
}

Using references in NUnit with Bamboo

I have a unit test (NUnit) which refers to a resource in a Visual Studio project. The test works correctly in Visual Studio, but when I try to run it with Bamboo, our build/CI server, this error occurs:


SetUp : System.BadImageFormatException : Could not load file or assembly 'IOHandlerLibrary, Version=1.0.5508.26943, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.


Bamboo is configured to run the DLL of the test project. It also has available in the same directory as the DLL the file which is being referenced by the resource.


Here is an example of how the resource is being accessed:



string superTruss = System.Text.Encoding.UTF8.GetString(IOHandlerUnitTests.Resource1.SuperTruss);

Using FakeItEasy to assert that an event was raised

I can do the following to verify if the ErrorOccurred event of my Consumer class was raised:



using System;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;

public interface IService
{
event EventHandler SomethingBadHappened;
}

class Consumer
{
private readonly IService service;

public Consumer(IService service)
{
this.service = service;
service.SomethingBadHappened += (sender, args) => RaiseErrorOccurred();
}

public event EventHandler ErrorOccurred;

protected virtual void RaiseErrorOccurred()
{
var handler = ErrorOccurred;
if (handler != null) handler(this, EventArgs.Empty);
}
}

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var service = A.Fake<IService>();
var consumer = new Consumer(service);

bool eventWasRaised = false;
consumer.ErrorOccurred += (sender, args) => { eventWasRaised = true; };

service.SomethingBadHappened += Raise.WithEmpty();

Assert.IsTrue(eventWasRaised);
}
}


I wonder if there is a more "Mocking Framework-y" way of doing this. Something like the below would be nice:



var service = A.Fake<IService>();
var consumer = new Consumer(service);

service.SomethingBadHappened += Raise.WithEmpty();

consumer.ErrorOccurred.MustHaveHappened(/*yada yada/*);

How to turn off Velocity unit testing in Meteor?

I'm using the mike:mocha package and I'm trying to figure out how to disable testing.


I tried going to packages > test-proxy > package.js and changing debugOnly to false, but after reloading the page it automatically changes it back to true.



Package.describe({
name: "velocity:test-proxy",
summary: "Dynamically created package to expose test files to mirrors",
version: "0.0.4",
debugOnly: true
});


What are steps that needs to be taken, for Velocity, before putting an app out to production?


Jasmine test for an array keeps failing

I'm trying to write a jasmine test to check if data is entered into an array. I have the view model, the unit (jasmine) test file, and the stage file to set up the information for the unit tests. The error that I am getting is saying that my array is undefined. The error message says "Expected undefined to be {SiteId: 0, FirstName: 'Jon', LastName: 'Walker', ObjectState: 1}"


This is my viewmodel. I am trying to test self.addPatient:



var EF = (function () {
return {
ObjectState: {
Unchanged: 0,
Added: 1,
Modified: 2,
Deleted: 3
}
};
})();

var patientMapping = {
'Patients': {
key: function (patient) {
return ko.utils.unwrapObservable(patient.PatientId);
},
create: function (options) {
return new PatientViewModel(options.data);
}
}
};

PatientViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);

self.flagPatientAsEdited = function () {
if (self.ObjectState() != ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
},
self.FullName = ko.computed(function () {
return (self.FirstName() + " " + self.LastName());
});
}

SiteViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, patientMapping, self);

self.save = function () {
$.ajax({
url: "/Site/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.siteViewModel != null) {
alert("Changes were saved successfully.");
ko.mapping.fromJS(data.siteViewModel, {}, self);
}
if (data.newLocation != null) {
window.location = data.newLocation;
}
}
});
},

self.flagSiteAsEdited = function () {
if (self.ObjectState() != ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
},

self.addPatient = function () {
var patient = new PatientViewModel({ SiteId: 0, FirstName: "", LastName: "", ObjectState: ObjectState.Added });
self.Patients.push(patient);
},

self.deletePatient = function (patient) {
self.Patients.remove(this);

if (patient.PatientId() > 0 && self.PatientsToDelete.indexOf(patient.PatientId()) == -1) {
self.PatientsToDelete.push(patient.PatientId());
}
};
}


This is my stage file to initialize information for the jasmine tests:



//staged data for view model testing

var OBP = OBP || {};

OBP.Testing = (function () {

var reset = function () {

var isReadOnly = true;

window.isReadOnly = true;
window.ObjectState = 2;
window.FirstName = "Joe";
window.LastName = "Mitchell";
window.SiteId = 5;
window.patient = { "SiteId": 0, "FirstName": "Jon", "LastName": "Walker", "ObjectState": 1 };
window.patientDelete = { "PatientId": 1, "SiteId": 0, "FirstName": "Frank", "LastName": "Smith", "ObjectState": 1 };
};

return {
reset: reset
};
})();

OBP.Testing.reset();


This is my jasmine test itself that is failing:



/// <reference path="../../lib/jasmine.js"/>
/// <reference path="../../lib/mock-ajax.js" />
/// <reference path="../../jquery-2.1.3.min.js" />
/// <reference path="../../lib/jasmin-jquery.js" />
/// <reference path="../../bootstrap.js" />
/// <reference path="../../knockout-3.2.0.js" />
/// <reference path="../../knockout.mapping-latest.js" />
/// <reference path="SiteViewModelStage.js" />
/// <reference path="../../siteviewmodel.js" />

describe("Add patient check:", function () {
beforeEach(function () {
OBP.Testing.reset()
});

var Patients = new Array();
var viewModel = new SiteViewModel({ patient: window.patient });

it("Add patient works", function () {
expect(Patients[0]).toBe(patient);
});
});


Any help debugging my jasmine test would be greatly appreciated.


Sonar Java - Is there a way to enforce unit test coverage?

Currently I have Sonar setup to show unit test coverage which works great. Is there a way to enforce a certain percentage of unit test coverage for a project? For example if the coverage drops below 50%, I want it to be a sonar violation and for my build to fail.


perl Test::Mock() how to return both a value and a function in a mockObject?

So I'm mocking results that I get back from a service call (I can't change the format of these results btw). In one case a call to getValue() returns an array of objects, but getValue()->getType() returns a string indicating what type of array I got.


Can anybody help me with how to mock this with a mockObject? I don't know how to make the mockObject both mock a method or return a value, this is what I have so far, obviously this won't work but I'm flumoxed as to how to get it to do what I need:



my $service;
my $mockService = sub {
my (@values) = @_;
$service = mockModule(
'Some::Service',
getValue => createMockObject (
return \@values;
getType => 'mytype'; #???
)
)
};


This is related to my other question -- I'm having a tough time mocking this particular aspect of this rather complex service!


Is it possible to have timeout for unit tests in js?

I'd like each test to terminate with an error if it takes more than 1 second.


I'm using Facebook's Jest library, write the tests in JSX and run them from Gulp (this means they run on node.js).


How to write a unit test with Jest for code with Promise

I am trying to write a unit test with Jest and Jasmine-pit for the below code and am totally stumped with it. The code is an ajax call which retrieves some data from resource and saves it in the variable.



init = function() {
var deferred = Q.defer();
$.ajax({
type: 'GET',
datatype: 'json',
url: window.location.origin + name,
success: function (data) {
userId = data.userId;
apiKey = data.apiKey;
deferred.resolve();
}
});
return deferred.promise;
},

JSP Folder Structure and General TDD

project



|
|utils

src

|
|main

| |utility.java
|
|test

| |utilityTest.java

|web

src

|
|main

| |web-inf

| |etc.


(I can't post images yet, so my apologies)


I have an example of what my folder structure currently looks like. The util folder structure has the main and test files separated, where the test files are only unit tests. The web folder structure currently only has a main, but does not have a test.


I understand that through HTTPUnit, or other xUnit, there is a way to have a testing framework. From what I understand, isn't it still considered acceptance testing? If this is so, then couldn't I just use an acceptance test framework, such as robot framework, to accomplish the same goal?


Also, would you setup the folder structure in the web project similar to that of the utils project? Having a main for the main files and test for the test files. In some projects, I have seen acceptance tests kept in a folder higher up in the structure above the src folders. Does it really matter on this folder structure?


OCMock Partial mock only for descendant class

I'm trying to set some unit test in our huge project. The problem is that some ViewControllers when called partial mock crash with following trace:



error: -[EspionageViewControllerTests testFillEspionageTabInfo] : failed: caught "NSInternalInconsistencyException", "-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "EspionageViewController" nib but the view outlet was not set."
0 CoreFoundation 0x0000000111264f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000110efdbb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000111264e6d +[NSException raise:format:] + 205
3 UIKit 0x000000010f68805f -[UIViewController _loadViewFromNibNamed:bundle:] + 441
4 UIKit 0x000000010f688588 -[UIViewController loadView] + 109
5 UIKit 0x000000010f6887f9 -[UIViewController loadViewIfRequired] + 75
6 UIKit 0x000000010f688c8e -[UIViewController view] + 27
7 AppName 0x000000010c07c388 -[IOViewController setTopBarView:] + 1144


As I understand I had problems with setTopBarView, and especially a place where I made following:



[viewElement setFrame:CGRectMake(viewElement.frame.origin.x, self.view.bounds.origin.y - viewElement.frame.size.height , viewElement.frame.size.width, viewElement.frame.size.height)];


So the self.view call makes this crash. My question is how can I avoid this situation - especially when my EspionageViewController is subclass of another ViewController where setTopBarView is defined. I need to use OCMPartialMock on EspionageVC as otherwise I won't be able to check it's methods, however it's super class(and methods) must be fully mocked to prevent those crashes. Any help will be apreciated.


Django unit tests mock

I am writing Django tests of one application and I came to the mock lib which I never used before. The problem is I need the response from server (the server is not actually there) if it is online or not. First of all I need to check that server id and ip and then check the state of it with the response of TRUE or FALSE. Server.object should come from models.py so I guess I need to start using mock lib here. The question is maybe some of you could explain me or show me few examples of getting fake response from 'mock'server.


Testing sending file to REST API

I'm building a REST API with Django REST Framework.


I have my models as follows:



class Mentor(Model):
name = CharField(max_length=100, verbose_name=u'Nome')
area = CharField(max_length=100, verbose_name=u'Área de Atuação')
website = URLField(max_length=500, verbose_name=u'Website')
description = TextField(verbose_name=u'Descrição')
picture = ImageField(upload_to=r'mentors', verbose_name=u'Foto')

class Meta:
verbose_name = u'Mentor'
verbose_name_plural = u'Mentores'


class NationalMentor(Mentor):
class Meta:
verbose_name = u'Mentor Nacional'
verbose_name_plural = u'Mentores Nacionais'


And the serializer is simple enough:



class MentorSerializer(ModelSerializer):
class Meta:
model = Mentor


class NationalMentorSerializer(ModelSerializer):
class Meta:
model = NationalMentor


I would like to test the API generated by this view:



class NationalMentorViewSet(ModelViewSet):
queryset = NationalMentor.objects.all()
serializer_class = NationalMentorSerializer


And this router:



router = DefaultRouter()
router.register(r'national-mentors', NationalMentorViewSet)

urlpatterns = router.urls


I'm trying this:



@override_settings(MEDIA_URL=r'/media/')
class NationalMentorTestCase(APISimpleTestCase):
def setUp(self):
NationalMentor.objects.create(id=1, name=u'Osvaldo', area=u'Educação',
website=r'http://ift.tt/1uIGEwv',
description=u'Descrição do Osvaldo.', picture=r'osvaldo.png')
NationalMentor.objects.create(id=2, name=u'Alice', area=u'Inovação',
website=r'http://www.alice.com.br',
description=u'Descrição da Alice.', picture=r'alice.gif')

def tearDown(self):
NationalMentor.objects.all().delete()

def test_create(self):
url = reverse(r'nationalmentor-list')
response = self.client.post(url,
{'name': u'Rafael', r'area': u'Desenvolvimento',
r'website': r'http://ift.tt/1veGliP',
r'description': u'Descrição do Rafael.',
r'picture': r'rafael.jpg'})
self.assertEqual(url, r'/national-mentors/')
self.assertEqual(response.data,
{r'id': 3, r'name': u'Rafael', r'area': u'Desenvolvimento',
r'website': r'http://ift.tt/1veGliP',
r'description': u'Descrição do Rafael.',
r'picture': r'http://testserver/media/rafael.jpg'})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)


But I'm getting this error:



======================================================================
FAIL: test_create (main.tests.test_national_mentor.NationalMentorTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/jpmelos/devel/ideation_admin/ideation_admin/main/tests/test_national_mentor.py", line 34, in test_create
r'picture': r'http://testserver/media/rafael.jpg'})
AssertionError: {'picture': [u'The submitted data was not a file. Check the encoding type on the [truncated]... != {'website': 'http://ift.tt/1veGliP', 'picture': 'http://testserver/media/rafa [truncated]...
- {'picture': [u'The submitted data was not a file. Check the encoding type on the form.']}
+ {'area': u'Desenvolvimento',
+ 'description': u'Descri\xe7\xe3o do Rafael.',
+ 'id': 3,
+ 'name': u'Rafael',
+ 'picture': 'http://testserver/media/rafael.jpg',
+ 'website': 'http://ift.tt/1veGliP'}

----------------------------------------------------------------------


I tried everything I could think of for last few hours, but couldn't find out how to test this API. How can I simulate a POST on this endpoint with the picture file for this NationalMentor and all the other data for creation of the instance?


$http is null when testing

I wrote a test that mocks a request to server which should return an array. The problem is, that when i launch my test it gives me error:



Cannot read property 'get' of null



and when i debug it is clear, that $http is null for some reason, but if i launch my code, it sends a request to server. Maybe my mystake is that i am using $http directly from controller, maybe i should use service for that and it would solve the problem? Anyway, my main question is why $http is null and what am i doing wrong?


Code in controller:


$scope.getLastReview = () => { $http.get('/lastReview').success((reviewArray: any) => { $scope.reviewsToShow = reviewArray; }); };


My test:



var sut = createController();
scope.getLastReview();
httpBackend.expectGET("/lastReview").respond(200, reviewArray);
httpBackend.flush();
expect(reviewArray.length).toBeGreaterThan(0);

Mocking the web browserorientationchange event to test bound event handler function with jasmine

I have an angularjs directive to create an event handler for the orientation change event to add a classname when the orientation change is landscape (it still needs improvement so bear with me for now):



angular.module('myApp')
.directive('orientationHandler', function ($rootScope, $timeout, $window) {
return function(scope, element, attrs) {
var className = 'mobile_landscape';
var mediaQuery = 'only screen and (max-width: 768px) and (orientation: landscape)';
var orientationCheck = function() {
if ($window.matchMedia(mediaQuery).matches) {
element.addClass(className);
$rootScope.$broadcast('Orientation.change', 'landscape');
} else {
element.removeClass(className);
$rootScope.$broadcast('Orientation.change', 'portrait');
}
};
$window.addEventListener('orientationchange', function() {
$timeout(orientationCheck, 100);
$timeout(orientationCheck, 200);
},
false
);
$rootScope.$on('$viewContentLoaded', function() {
$timeout(orientationCheck, 100);
$timeout(orientationCheck, 200);
});
};
});


Now I would like to test on jasmine such a directive:



//TODO: Find a way to test orientation change events
describe('Directive: orientationHandler', function () {

// load the directive's module
beforeEach(module('myApp'));

var element,
scope,
$window;

beforeEach(inject(function ($rootScope, $compile, $httpBackend, _$window_) {
$window = _$window_;
scope = $rootScope.$new();
element = angular.element('<div orientation-handler></div>');
element = $compile(element)(scope);
$httpBackend.whenGET(/.*/).respond(200);
}));

it('should broadcast an event when changed the orientation', function () {
var message;
scope.$on('Orientation.change', function(event, value) {
message = value;
});
angular.element($window).trigger('orientationchange');
scope.$apply();
expect(message).toBeDefined();
expect(angular.isString(message)).toBe(true);
});
});


So, is there a way to programatically trigger the orientation change event, or mocking it somehow to test the bound event handler?


Thanks!


How to remove duplication in the script files loaded in index.html and karma?

I have a project that was initially created using the yeoman angularjs generator. I run my unit-tests using karma and currently whenever I add a new script to the index.html I also need to add it to the karma.conf.js file so it is accessible for me to test. I don't like this duplication, it slows me down and it is error prone (e.g. I can add it to index.html and forget to add it to karma.conf.js).


The example projects that I see do something like this in the karma.conf.js:



files: [
'app/bower_components/jquery/jquery.js',
'app/bower_components/lodash/dist/lodash.js',
'app/scripts/**/*.js',
'test/spec/**/*.js'
]


That is fine for test specs but not for actual application scripts because the order matters there. Also they have to specifically specify each bower component because the order also matters there


I thought about creating a task that copies the file paths from index.js and modifies and adds it to karma.conf.js before I run the unit-tests, but before I do that I thought I would ask if anyone knows a better way to remove/manage this duplication.


I know if I was using a file and module loader I would not have this issue, but I don't intend to use that at least for now.


RavenDb connectionstring memory=true not working

I'm trying to setup unit tests for a Web Api app with RavenDb.Client. The app is using a RavenDb server running as a service and works just fine.


In my test project I've set the connection string to Memory=True, but the tests throws an exception saying that "memory" is an unknown option.


What am I doing wrong?



<connectionStrings>
<add name="RavenDbConnectionString" connectionString="memory=1"/>
</connectionStrings>


IDocumentStore store = new DocumentStore()
{
ConnectionStringName = "RavenDbConnectionString"
}.Initialize();

Grails test-app is not executing statement

I am writing unit test case for service class. There is one method called getMemberStatusAndCurrentProducts. I have full filled both the conditions but still it is not executing inner statements of this condition.



Map getMemberStatusAndCurrentProducts(Member member) {
def results = [:]

results.memberId = member.id
results.firstName = member.contactInfo.firstName
results.lastName = member.contactInfo.lastName
results.status = member.status
results.email = member.contactInfo.email

if (member.status == MemberStatusType.EXPIRED) {
results.products = (member.activeEnrollments.originatingOffer*.products)?.flatten()?.unique()?.sort() { it.name }
results.offerGroup = (member.activeEnrollments.originatingOffer*.offerGroup)?.flatten()?.unique()?.sort() { it?.name }
} else {
results.products = (member.activeEnrollments.originatingOffer*.products)?.flatten()?.unique()?.sort() { it.name }
results.offerGroup = (member.activeEnrollments.originatingOffer*.offerGroup)?.flatten()?.unique()?.sort() { it?.name }
}

return results
}


The if condition is shown covered but these statements are shown as uncovered



if (member.status == MemberStatusType.EXPIRED) {
results.products = (member.activeEnrollments.originatingOffer*.products)?.flatten()?.unique()?.sort() { it.name }
results.offerGroup = (member.activeEnrollments.originatingOffer*.offerGroup)?.flatten()?.unique()?.sort() { it?.name }
} else {
results.products = (member.activeEnrollments.originatingOffer*.products)?.flatten()?.unique()?.sort() { it.name }
results.offerGroup = (member.activeEnrollments.originatingOffer*.offerGroup)?.flatten()?.unique()?.sort() { it?.name }
}


Where activeEnrollments is method of Member domain, originatingOffer is an object of Offer domain. I am using test-app -coverage :unit <service_class> command to run unit test.


Can anyone help me in this issue.


How to reset mock/spy partially?

I want to reset only method count in spy.


Is it possible?


I know that exists method



Mockito.reset


But it resets mock entirely.


Python Mock patch.multiple argument names

It's possible to change the test argument name of a patched class or function when using patch as a decorator.



@patch('module.ClassName2')
@patch('module.ClassName1')
def test(MockClass1, MockClass2):
MockClass1.test.return_value = 'testing'


However, I can't seem to find in the documentation how to differentiate the original object and the mock when using patch.multiple.



@patch.multiple('module.ClassName', foo=DEFAULT, bar=DEFAULT)
def test(foo, bar):
foo.return_value = 'foo'


In the above example, the arguments in the test must be foo and bar. Is there any clean way to allow their use with a clearer differentiation, e.g. mock_foo?


This would also be handy in cases where the original class or method is needed in part of the test, avoiding imports like from module import Class as OriginalClass


Thanks in advance.


Saving unit test results after running tests

In Visual Studio 2013, running all my Visual Studio unit tests shows the test results, together with callstack, exception information and a stack trace of failing tests. Is there any way of saving the test results, after test execution, such that I can open up previously run tests?


I have read posts that explain that failing test results are kept, in the TestResults folder, while successful tests are deleted. Unfortunately neither failing nor successful test results remain, in my TestResults folder, after running the tests.


I tried creating and using a .runsettings file and setting the element to false, but this didn't change anything.


Anyone know how to keep the test results, for later inspection?


Unit testing in Universal App

I create new Universal App project, structure of the solution on screenshot.


enter image description here


After I add Unit Test App project for Windows Phone.


enter image description here


And see Could not find SDK "MSTestFramework, Version=14.0"


enter image description here


I'm use Visual Studio 2015 CTP



Microsoft Visual Studio Ultimate 2015 CTP
Version 14.0.22512.0 DP
Microsoft .NET Framework
Version 4.6.00007


How to solve the problem?


How to do internal interfaces visible for Moq?

I have 3 project in my C# solution.



  • Signatures

  • Structures

  • Tests


Signatures has public and internal interfaces. Also it has



[assembly: InternalsVisibleTo("Structures")]
[assembly: InternalsVisibleTo("Tests")]


in AssemblyInfo.cs of.


Structures has public and internal classes and



[assembly: InternalsVisibleTo("Tests")]


in AssemblyInfo.cs of.


Tests has next source:



<packages>
<package id="Moq" version="4.2.1409.1722" targetFramework="net45" />
<package id="NUnit" version="2.6.4" targetFramework="net45" />
<package id="NUnitTestAdapter" version="1.2" targetFramework="net45" />
</packages>


as NuGet packages in packages.config.


I wrote some unit test for internal interface from Signatures and internal class from Structures. Run, and had next result: exception:


Type Signatures.InterfaceX is not visible to DynamicProxy. Can not create proxy for types that are not accessible. Make the type public, or internal and mark your assembly with [assembly: InternalsVisibleTo(InternalsVisible.ToDynamicProxyGenAssembly2)] attribute.


Seems logical. I added [assembly: InternalsVisibleTo("InternalsVisible.DynamicProxyGenAssembly2")] to assembly info of Signatures and Structures projects. Run, and had next result: exception:


Type 'Castle.Proxies.IReminiscenceableDataTableProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface.


This was to help, but didn't. Only change exception message.


How to fix my problem?


How to test call expectation in Go

I have a class MyClass that I want to test.


MyClass has a void method that calls an inner server to do something.



func (d *MyClass) SendToServer(args)
do stuff....
server.Send(myMessage)


I want to mock the server call Send, but since the method is a void method I can't be sure that I am actually calling it right.


These are the options I had in mind:



  1. Use gomock, mock the server, and set expectations on the send method of the service

  2. create my own MockServer, and "override" the method Send with a bunch of verifications. Something like:


func (d *MockedServer) Send(message) // verify message...



  1. create my own MockServer, but instead of verifying the expectation within the method, add the message to a list of messages, and then verify the content of the list.


What is a better approach in Go?


Experiments as unit test?

I've a bunch of python scripts and functions that I need to run for several experiments, with varying input data and output-to-file dumping. For this post an experiment is a triple consisting of input data, a (one or several) method call on the input data and a dump_results procedure.


At the moment I'm abusing unittest to get things done and bundle several experiments as test suites. For instance my file could look like this:



def experiment1():
pass
def experiment2():
pass
...

if __name__ == '__main__':
unittest.TextTestRunner().run(my_experiments_bundle_1)


where my_experiments_bundle_1 is a TestSuite containing all my relevant tests, for instance experiment1 and experiment2.


However, it's a slight abuse of the unittest paradigm as I'm actually not testing the correctness of implemented functionality but rather how the implementation acts on the given input data.


I've found experimentator and expsuite but...


a) I would like to use as few external packages as possible, for easy reproducibility and sharing of the code.


b) it seems to be a bit overkill for my purpose.


Nevertheless, a simple way to store parameters in an xml-like config would be a nice-to-have feature, though optional.


Q: What is a recommended/established and simple way or framework to bundle and manage such experiments? Are there any best practices?


Q: What are possible pitfalls abusing unittest for this purpose?


Thanks


PS: Slightly related is [question 1322414] and [question 14740373], but the former is more about organizing code tests in Java and the latter deals with design of experiments, using pyDOE, which looks to me as aiming particularly at statistics people. (sry, I'm not allowed to post more than two links)


Unit tests for Oracle database view

We have few database views to simplify or (in most cases) improve performance of an application. Each view contains some business logic that we don't know how to test by unit tests. Is there some way to write unit tests for database views? We use dbunit with hsqldb to test sql queries. With these tools we can create view directly from code using Hibernate but it's not that easy. HSQLDB has different syntax than Oracle so we can't use native oracle sql to write it. We can use HQL but we can make some mistakes during rewriting native oracle sql to HQL and unit tests won't be valuable.


First async unit test with Mocha and Sinonjs

I m actually using a micro framework created by my society in which we use Mongoose.


To manage the mongoose object, we created a modelfactory, that returns us a model corresponding to the mongoose name object.


Actually, I m working on an authentication service in which I inject this modelfactory.


I need to unit test it with mocha and sinonjs, but I m a bit lost...


This is my authentication Service method that I want to test :



class AuthenticationService extends Service

constructor: (modelFactory)->
super(modelFactory)

@authorizedClientIds = [
"123456"
"toto"
]
@OAuthAccessTokensModel = @modelFactory.getSchema('OAuthAccessTokens')
@OAuthClientsModel = @modelFactory.getSchema('OAuthClients')
@OAuthUsersModel = @modelFactory.getSchema('OAuthUsers')
@OAuthRefreshTokensModel = @modelFactory.getSchema('OAuthRefreshTokens')

## Get an access token from the bearer token ##
getAccessToken: (bearerToken, callback)->
@OAuthAccessTokensModel.findOne({accessToken: bearerToken}, callback)

module.exports = AuthenticationService


I want to test the getAccessToken method, but I have clearly no idea how to make it work...


I've tried to make something like :



describe("Authentication Service", function () {

var service;

before(function () {
ModelFactory = use('/app/core/config/database/ModelFactory');

var mock = sinon.mock(ModelFactory.getFactoryInstance([]));
mock.expects("getSchema").withArgs("user").return({name:'user',getName:function(){}});

service = new AuthenticationService(mock);
});

describe("getAccessToken", function () {
it('should return-1 when the value is not present', function () {
var proxy = once(service.getAccessToken());

mock.verify();
});
});
});


How should I do to test it correctly ?


Thanks for advance


Facing Issue with Unit testing in Grails

I need to get messagesource to get access message.properties file in simple groovy class(Exception class) so that i am using Holders.getGrailsApplication(). My problem is Holders.getGrailsApplication() is getting null when i execute unit test case.It works fine if i deploy it in web server. Variable :-



static def grailsApplicationCntx=Holders.getGrailsApplication().getMainContext().getBean(‘messageSource’)


Error:-



`Failure: testActivateService_Case1(com.xyz.ActivationServiceTests)
| java.lang.ExceptionInInitializerError
at java.lang.Class.forName(Class.java:186)
at com.xyz.DatabaseService.addBankUser(DatabaseService.groovy:11)
at com.xyz.RegisterService.register(RegisterService.groovy:39)
at com.xyz.ActivationServiceTests.setUp(ActivationServiceTests.groovy:60)
Caused by: java.lang.NullPointerException: Cannot invoke method getMainContext() on null object
at com.xyz.exception.Exception.(Exception.groovy:55)
… 4 more

jeudi 29 janvier 2015

Unit Testing /login in Spring MVC using MockMvc

I have a very simple REST application created using Spring MVC. (Code is available at GitHub.) It has a simple WebSecurityConfigurer as follows:



@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/user/new").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.logout()
.permitAll()
.logoutSuccessHandler(logoutSuccessHandler);
}


When I run the application, both the custom controllers and the login/logout pages work without a problem. I can even unit test /user/new via MockMvc. However, when I try to test /login with the following function



@Test
public void testUserLogin() throws Exception {
RequestBuilder requestBuilder = post("/login")
.param("username", testUser.getUsername())
.param("password", testUser.getPassword());
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andExpect(cookie().exists("JSESSIONID"));
}


it fails as follows:



MockHttpServletRequest:
HTTP Method = POST
Request URI = /login
Parameters = {username=[test-user-UserControllerTest], password=[test-user-UserControllerTest-password]}
Headers = {}

Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
Was async started = false
Async result = null

Resolved Exception:
Type = org.springframework.web.HttpRequestMethodNotSupportedException

ModelAndView:
View name = null
View = null
Model = null

FlashMap:

MockHttpServletResponse:
Status = 405
Error message = Request method 'POST' not supported
Headers = {Allow=[HEAD, GET]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: Status expected:<200> but was:<405>


But I am pretty user POST to /login is working when I run the application instead of test. Further, when I try make a GET or HEAD request (as suggested in the Headers = {Allow=[HEAD, GET]} line of the logs), this time I receive a 404. Any ideas about what is going on and how can I fix it?


how to unit test a ngcontroller with external dependencies in jasmine?

I am trying to write a karma unit test for a angularcontroller, this is the controller. Using a fileupload from here (http://ift.tt/1aM2BiP):



var c, di;

c = function($scope, FileUploader, UploadHelper, currentUser) {
var uploader;

$scope.uploader = uploader = new FileUploader(UploadHelper.getOptions());

uploader.onSuccessItem = function(item, response, status, headers) {
//do something
};
return this;
};

di = [ '$scope', 'FileUploader', 'UploadHelper', 'currentUser', c];

angular.module('mycontrollers').controller('DocumentsController', di);


My jasmine test looks like this:



describe('Customer: Controller: DocumentsController', function() {
var $rootScope, DocumentMock, UserMock, documentsController, scope;
documentsController = $rootScope = scope = DocumentMock = UserMock = null;

beforeEach(function() {
module("mycontrollers");
return inject(function($controller, _$rootScope_, $q) {
var deferred, documents, fileUploader, uploadHelper, user;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
documents = [
{
id: "doc 1",
documentType: "other"
}, {
id: "doc 2",
documentType: "pdf"
}, {
id: "doc 3",
v: "pdf"
}
];
user = {
id: 'user_id',
username: 'username'
};
UserMock = {
currentUser: function() {
return user;
}
};
fileUploader = {};
uploadHelper = {};

return documentsController = $controller('DocumentsController', {
documents: documents,
$scope: scope,
FileUploader: fileUploader,
UploadHelper: uploadHelper,
currentUser: UserMock

});
});
});
return describe("On creation", function() {
return it("should assign documents to scope", function() {
return expect(1).toEqual(1);
});
});
});


The problems start on the line with $scope.uploader. I get an error like this:



'DocumentsController not defined'


Question is how I can mock functions like uploaderHelper.getOptions in my test so this unit test will be successful?


tcltest unit tests: how to check if constraint is active to enable code reuse

We are using tcltest to do our unit testing but we are finding it difficult to reuse code within our test suite.


We have a test that is executed multiple times for different system configurations. I created a proc which contains this test and reuse it everywhere instead of duplicating the test's code many times throughout the suite.


For example:



proc test_config { config_name} {
test $test_name {} -constraints $config_name -body {
<test body>
} -returnCodes ok
}


The problem is that I sometimes want to only test certain configurations. I pass the configuration name as a parameter to the proc as shown above, but the -constraints {} part of the test does not look up the $config_name parameter as expected. The test is always skipped unless I hard code the configuration name, but using a proc is not possible and I would need to duplicate the code everywhere just to hardcode the constraint.


Is there a way to look if the constraint is enabled in the tcltest configuration?


Something like this:



proc test_config { config_name} {
testConstraint X [expr { ::tcltest::isConstraintActive $config_name } ]
test $test_name {} -constraints X -body {
<test body>
} -returnCodes ok
}


So, is there a function in tcltest doing something like ::tcltest::isConstraintActive $config_name?


Perl unit test: mockModule needs to mock returning an array of objects with a 'getType' method

I'm attempting to make a unit test for perl code to mock a service which returns an array containing objects which also need to be mocked because they have a method getType() which I need to mock.


So the code which processes the results of this service call looks something like this:



foreach my $set (@{$serviceResults->getValue()}) {
next unless ($set->getType() eq 'type');
...
}


and I'm trying to mock the service like so:



my $service;
my $mockService = sub {
my (%resultValues) = @_;
$service = mockModule(
'My::Service',
getValue => createMockObject(
# how to mock the getType method?
)
)
};


And then I create a mock like this:



$mockService->([
{type=>'a', data=>[0, 5]},
{type=>'b', data=>[2, 3]}]);


So how do I create the mock of the getType method on each hash object in the array? This array changes depending on the unit test, I can't use a fixed size array.


MongoDB / Mongoose Unit Testing

I'm writing a npm package to import GIS data into MongoDB via mongoose. I've written unit tests using mocha to test the data transformations that happen BEFORE the mongoose model is saved.


However, I'd like to be sure that all the mongoose data got saved correctly to the database (including any updates that needed to occur). How should I do this?


I'm thinking the correct way to go would be to create a test collection, insert all the records, ensure that it looks the way I expect it to look, and drop the collection. Is this the best practice? Does anyone have a code sample or a model npm package / library I should be modelling mine after?


How do Test HttpWebRequest Depended method?

I have this class:



public class RestClient
{
public RestClient()
{ }

protected virtual HttpWebRequest CreateHttpWebRequest(Uri uri)
{
return (HttpWebRequest)HttpWebRequest.Create(uri);
}


/// <summary>
/// Perform a http POST request in order to push data to server
/// </summary>
/// <param name="uri">End Point Uri</param>
/// <param name="data">Data to be transmitted</param>
/// <returns></returns>
///
public long PostRequest(Uri uri,string data)
{

try
{
HttpWebRequest request = CreateHttpWebRequest(uri); //(HttpWebRequest)HttpWebRequest.Create(uri);

request.Method = "POST";
request.ContentType = "application/json";

System.Text.UTF8Encoding encoding = new UTF8Encoding();

byte[] bytes = encoding.GetBytes(data);



using (Stream requestStream = request.GetRequestStream())
{
//Transmit data
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
}



//Get the Response from the server
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
{
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
}
}


return request.ContentLength;
}
catch (Exception e)
{
throw e;
}

}

}


And would like to Unit test (using nunit) the PostRequest Method.


Doing some research, I could found some way to mock the HttpWebRequest in this post (Is it possible to mock out a .NET HttpWebResponse?) and a way to inject it into the class in this post (How to unit test a method with HttpWebRequest/Response dependencies).


However, when I tried to test my method I got this error:



System.InvalidCastException : Unable to cast object of type 'Castle.Proxies.IHttpWebRequestProxy' to type 'System.Net.HttpWebRequest'.


in this line of my test



client.HttpWebRequestFake = (HttpWebRequest)factory.Object.Create("http://127.0.0.1");


That is my test code:



public class TesableRestClient : RestClient
{
public HttpWebRequest HttpWebRequestFake { get; set; }

protected override HttpWebRequest CreateHttpWebRequest(Uri url)
{
if (HttpWebRequestFake != null)
return HttpWebRequestFake;
return base.CreateHttpWebRequest(url);
}
}


[TestFixture]
public class TransferWebRequestTest
{
[Test]
public void TestPostResquest()
{
string expectedContent = "Content";
var expectedBytes = Encoding.UTF8.GetBytes(expectedContent);
var responseStream = new MemoryStream();
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
responseStream.Seek(0, SeekOrigin.Begin);

var response = new Mock<IHttpWebResponse>();
response.Setup(c => c.GetResponseStream()).Returns(responseStream);

var request = new Mock<IHttpWebRequest>();
request.Setup(c => c.GetResponse()).Returns(response.Object);

var factory = new Mock<IHttpWebRequestFactory>();
factory.Setup(c => c.Create(It.IsAny<string>()))
.Returns(request.Object);

TesableRestClient client = new TesableRestClient();
client.HttpWebRequestFake = (HttpWebRequest)factory.Object.Create("http://127.0.0.1");

// DoStuff call the url with a request and then processes the
long bytesSent = client.PostRequest(new Uri("http://127.0.0.1"), expectedContent);
Assert.AreEqual(expectedBytes, bytesSent);
}


The HttpWebRequest/Response is this:



public interface IHttpWebRequest
{
// expose the members you need
string Method { get; set; }
string ContentType { get; set; }
long ContentLength { get; set; }
IHttpWebResponse GetResponse();
}

public interface IHttpWebResponse : IDisposable
{
// expose the members you need
HttpStatusCode StatusCode { get; }
string StatusDescription { get;}
Stream GetResponseStream();
}

public interface IHttpWebRequestFactory
{
IHttpWebRequest Create(string uri);
}

// barebones implementation

public class HttpWebRequestFactory : IHttpWebRequestFactory
{
public IHttpWebRequest Create(string uri)
{
return new WrapHttpWebRequest((HttpWebRequest)WebRequest.Create(uri));
}
}

public class WrapHttpWebRequest : IHttpWebRequest
{
private readonly HttpWebRequest _request;

public WrapHttpWebRequest(HttpWebRequest request)
{
_request = request;
}

public string Method
{
get { return _request.Method; }
set { _request.Method = value; }
}

public string ContentType
{
get { return _request.ContentType; }
set { _request.ContentType = value; }
}

public long ContentLength
{
get { return _request.ContentLength; }
set { _request.ContentLength = value; }
}

public IHttpWebResponse GetResponse()
{
return new WrapHttpWebResponse((HttpWebResponse)_request.GetResponse());
}
}

public class WrapHttpWebResponse : IHttpWebResponse
{
private HttpWebResponse _response;

public WrapHttpWebResponse(HttpWebResponse response)
{
_response = response;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (disposing)
{
if (_response != null)
{
((IDisposable)_response).Dispose();
_response = null;
}
}
}

public Stream GetResponseStream()
{
return _response.GetResponseStream();
}

public HttpStatusCode StatusCode
{
get { return _response.StatusCode; }
}

public string StatusDescription
{
get { return _response.StatusDescription; }
}

}


Any idea of how I could solve this?


Thank you