mardi 31 mai 2016

What to do if DbSet

I am pretty new with entity framework, i have db first approach and i am setting the values of my model into the DbSet MyClassName. But when i am running it is giving exception that "myContext.MyClassName is null Additional information: "Object reference not set to an instance of an object.", i tried many solution but unable to create object of my DbSet.

**1st Tried**

MyClass myObj = new MyClass();
myObj.Id = stud.Id;
myObj.StudId = stud.StudId;
myObj.CourseId = stud.CourseId;

myContext.MyClass.Add(myObj) //Here exception starts with messages.


**2nd Tried**
MyClass langTest = new MyClass();
langTest.Id = 1;
langTest.StudentId = 500;
foreach(MyClass entity in myContext.MyClass)// Here getting exception because MyClass instance is null.
{
   var entry = _context.Entry(langTest);
   if (entry.State == EntityState.Detached)
   {
      myContext.MyClass.Add(entity);
   }
}

If any solution or suggestion please put comment, highly appreciated.

Testing Thumbnailator in Play (Scala)

To start off, let me just say that I am fairly new to Scala and Play. I've been tasked with writing tests for Thumbnailator. These tests are geared to make sure that images uploaded are resized to 400x400 from the CENTER of the image (was able to find solution to image position from: Using Thumbnailator, can i make thumbnail with same height and width regardless the image size).

I've seen unit tests in Scala before, but have not written anything to test a plugin. The plugin itself does not seem to have much documentation on how to test functionality. Is anyone smarter than myself able to provide me some guidance on how I would begin this?

Thank you.

How to properly test a module that requires newrelic with jest

I'm working migrating a bunch of unit tests from mockery to jest. When I jest a module that requires the new relic agent like so: require('newrelic'), I get downstream errors like :

  - TypeError: Cannot convert undefined or null to object
    at Object.<anonymous> (node_modules/newrelic/lib/config.js:165:33)
    at Runtime._execModule (node_modules/jest-cli/src/Runtime/Runtime.js:261:17)
    at Object.<anonymous> (node_modules/newrelic/lib/logger.js:18:14)
    at Object.<anonymous> (node_modules/newrelic/index.js:3:14)

What is the best way to deal with modules like newrelic which jest has a hard time mocking? What have other people done when they have both jest and newrelic in their stack?

How to generate junit tests given an XSD

Currently our XSD schema changes quite a bit and we want to it to create junit tests that will break whenever an existing data type gets re-defined.

For example, if there was a field "YearBuilt" defined as a "Integer" originally and someone comes along and changes this to be a "String", we want this jUnit test to fail.

Is there any utilities or programs which will take in an existing schema and generate the appropriate unit tests for all the datatypes? We currently generate jaxb objects. Is there some program which can generate junits for a set of jaxb objects?

Checking Mock Parameter with Spock

I am unit testing some existing code and I have just started learning Spock.

I am trying to verify the SUT calls a Collaborator correctly, the method takes a Function as an argument which is generated by SUT.

What is the best way to check that the function is behaving as expected?

I've tried the below, which validates SUT calls its collaborator the correct number of times with a Function, which seems ok, but

def collab = Mock(Collab)
def sut = new SUT(collab)
def input = new Mock(Input)

def "..."() {

    when:
        sut.generatesAFunctionAndCallsCollab(input)
    then:
        1 * input.methodCalledInFunction() >> inputRetn
        1 * collab.methodCall({ Function fun ->
            assert fun.apply(input) == expectedResult
        })
    where:
        inputRetn | expectedResult
        true      | false
        false     | true
}

Finally, how could I refactor the closure into one place to reuse across tests?

How to fake IP address in Meteor.Method for testing with chai?

I have a method to store a vote for a specific dataset into the database. If the same dataset has already been added to the database, the IP address is stored in an array in the dataset. If the IP is already in the array the method should throw an error. If the length of the array is over a treshold, the dataset is stored into another collection.

Meteor.methods({
  'validate'(dataset){
     check(dataset, datasetSchema);
     if (!this.connection) {
       throw new Meteor.Error('This method should not be called from the server.');
     }
     if (Meteor.call('notInDatabase', dataset)) { //true if not in database
       dataset.votes = [this.connection.clientAddress];
       MyCollection.insert(dataset);
     } else {
       const datasetFromDB = MyCollection.findOne({hashId: dataset.hashId});
       if(_.contains(datasetFromDB.votes, this.connection.clientAddress)){
         throw new Meteor.Error('Already voted');
       }
       if(compareDatasets(dataset, datasetFromDB)){
         MyCollection.update({_id: datasetFromDB._id}, {$push: {votes: this.connection.clientAddress});
         if(dataset.votes.length + 1 >= treshold){
           //do something
         }
       }
    }         
  }
});

I want to test this method with meteor/practicalmeteor:chai. In order to do this, I have to 'fake' different IP addresses. Is there a way to do this with chai? The only solution I could come up with is to use Meteor.isTest in the method, but it doesn't feel right.

Android Studio. Two similar tests, yet one passes the other fails

I'm new to Android studio and Java in general.

Im currently doing a test class and these two code are very similar(only change in layout variable) but 2 different results. Using Roboelectric.

This one passes

/*Test to verify next button */
@Test
public void checkNextButton(){
    /* Simulate button press */
    activity.findViewById(R.id.nextButton).performClick();

    /*Capture view*/
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    View view = shadowActivity.findViewById(android.R.id.content);

    /*Check view is not null*/
    assertNotNull(view);
}

This one fails.

/* Test to verify back button */
@Test
public void checkBackButton() {
    /* Simulate button press */
    activity.findViewById(R.id.backButton).performClick();

    /*Capture view*/
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    View view = shadowActivity.findViewById(android.R.id.content);

    /*Check view is not null*/
    assertNotNull(view);

}

The only difference is in the following line,

activity.findViewById(R.id.****Button).performClick();

I've double check the button Id and both only change the screen to the needed layout. I cannot think of a valid why one would pass while the other fails.

The console shows the following,

java.lang.NullPointerException at com.presentech.handsup.AudienceTutorialTest.checkBackButton(AudienceTutorialTest.java:69) 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:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251) at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188) at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74) 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:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

How to Unit Test a method using CountDownLatch?

I need to do the Unit Test of below code which is using countdownlatch. This is a test code only. I am using mockito thenAnswer and InvocationOnMask for mocking threads/callable. But I don't know how to initialize/mock or exit countdownlatch in unit testing.

public class ThreadPoolTaskExecRunner {
    private ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    private ArrayBlockingQueue<String> values = new ArrayBlockingQueue<String>(100, true);

    public ThreadPoolTaskExecRunner() {
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
    }

    public static void main(String args[]) {
        ThreadPoolTaskExecRunner obj = new ThreadPoolTaskExecRunner();
        obj.testCountDownLatch();
    }
    public void testCountDownLatch() {
        final CountDownLatch latch = new CountDownLatch(5);
        Future<String> future1 = threadPoolTaskExecutor.submit(new Task("A", values, latch));
        Future<String> future3 = threadPoolTaskExecutor.submit(new Task("B", values, latch));
        Future<String> future4 = threadPoolTaskExecutor.submit(new Task("C", values, latch));
        Future<String> future5 = threadPoolTaskExecutor.submit(new Task("D", values, latch));
        Future<String> future2 = threadPoolTaskExecutor.submit(new Task("E", values, latch));

        try{
            latch.await();  //main thread is waiting on CountDownLatch to finish
        }catch(InterruptedException ie){
            System.out.println(ie);
        }
        System.out.println("*********** DONE *********** values size= "+values.size());
        for(String s : values)
            System.out.println(s);
        threadPoolTaskExecutor.shutdown();
    }

    public static class Task implements Callable<String> {
        private String type;
        private ArrayBlockingQueue<String> values;
        private CountDownLatch latch;

        public Task(String s, ArrayBlockingQueue<String> values, CountDownLatch latch) {
            this.type = s;
            this.values = values;
            this.latch = latch;
        }

        @Override
        public String call() throws Exception {
            try {
                System.out.println("Inside call type: " + type);
                Thread.sleep(10);
                values.add(type);
                return type;
            } finally {
                if(latch != null)
                    latch.countDown();
            }
        }
    }
}

I developed the Unit Test class, But it is not helpful ...

@RunWith(MockitoJUnitRunner.class)
public class ThreadPoolTaskExecRunnerTest {
    @Mock
    private ThreadPoolTaskExecutor taskExecutor;

    @InjectMocks
    ThreadPoolTaskExecRunner threadPoolTaskExecRunner;

    @Test
    public void test() {
        when(taskExecutor.submit(any(ThreadPoolTaskExecRunner.Task.class))).thenAnswer(new Answer<Future<String>>() {
            public Future<String> answer(InvocationOnMock invocation) throws Throwable {
                Future<String> future = mock(FutureTask.class);
                when(future.isDone()).thenReturn(false, false, true);
                when(future.get()).thenReturn("This is a test");
                return future;
            }
        });

        threadPoolTaskExecRunner.testCountDownLatch();
    }
}

How can I properly parallellize my test suites in TeamCity?

So I have a scenario whereby I have many different test suites. They are all triggered by a Create Test Environment step. However, these test suites cannot run concurrently on the same environment, as they would interfere with each other. To alleviate this, I added a shared resource in TeamCity and configured the build definitions to block on this resource, so that only one test suite runs at a time. This works.

However, if while the test suites for Environment A are running, another code change is checked in, Environment B can be created by the Create Test Environment step, and all the test suites are re-queued. Currently, due to the fact that they all share a shared resource that they block on, those tests then sit in the queue awaiting access to the shared resource. However, there is no reason that the tests for Environment B cannot run (one build at a time) in parallel with the tests for Environment A. How can I best tweak my TeamCity configuration to achieve this?

Assert that a PropertyMock was called on a specific instance

I have successfully mocked a property with PropertyMock, but I can't figure out how to check which instance of the class has had that property called. How can I assert that the property was called on one object, but not on another?

Here's an example where I want to assert that foo1.is_big was called, and foo2.is_big was not:

from mock import PropertyMock, patch


class Foo(object):
    def __init__(self, size):
        self.size = size

    @property
    def is_big(self):
        return self.size > 5

f = Foo(3)
g = Foo(10)
assert not f.is_big
assert g.is_big

with patch('__main__.Foo.is_big', new_callable=PropertyMock) as mock_is_big:
    mock_is_big.return_value = True
    foo1 = Foo(4)
    foo2 = Foo(9)

    should_pass = False
    if should_pass:
        is_big = foo1.is_big
    else:
        is_big = foo2.is_big
    assert is_big
    # How can I make this pass when should_pass is True, and fail otherwise?
    mock_is_big.assert_called_once_with()

print('Done.')

The current code will pass when either one of them is called.

Double parameterization

So I have a set of tests where I'd like to test multiple versions of a solution. Currently I have

import pytest

import product_not_at_index


functions_to_test = [
    product_not_at_index.product_not_at_index_n_squared,
    product_not_at_index.product_not_at_index,
]

def run_test(function_input, expected_result, test_func):
    actual_result = test_func(function_input)
    assert actual_result == expected_result

@pytest.mark.parametrize("test_func", functions_to_test)
def test_empty_list(test_func):
    input_data = []
    expected_result = []
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_single_item(test_func):
    input_data = [1]
    expected_result = [1]
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_one_times_one(test_func):
    input_data = [1, 1]
    expected_result = [1, 1]
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_normal_use_case(test_func):
    input_data = [1, 7, 3, 4]
    expected_result = [84, 12, 28, 21]
    run_test(input_data, expected_result, test_func)

And this works great. But looking at my solution I see that all of my tests have the same basic set of code. How can I parameterize a function twice so that I can just have a single test function and stop repeating myself?

I thought that I could do something like

import pytest

import product_not_at_index


functions_to_test = [product_not_at_index.product_not_at_index_n_squared]
test_data = [
    [], [],
    [1], [1],
    [1, 1], [1, 1],
    [1, 7, 3, 4],  [84, 12, 28, 21],
]

@pytest.mark.parametrize("function_input,expected_result", test_data)
@pytest.mark.parametrize("test_func", functions_to_test)
def test_run(function_input, expected_result, test_func):
    actual_result = test_func(function_input)
    assert actual_result == expected_result

but that just returns this error

E   assert 0 == 2
E    +  where 0 = len([])
E    +  and   2 = len(['function_input', 'expected_result'])

PHPUnit - assert method call order on different mocks

I would like to test a method that just call a method of my entity object and persists it to the database.

public function setNameAndPersistObject($entityObject) {
    $entityObject->setName("John");
    $this->entityManager->persist($entityObject);
}

I would like to test the call order of the called methods, to test that 'persist' gets called after 'setName', so the new name "John" gets saved in the database. How would I do that in PHPUnit?

How to use Minitest mock

Trying to test class method using Minitest::Mock

Included minitest in my Gemfile in development and test environments and bundled:

group :development, :test do
  gem 'byebug'
  gem 'minitest-rails'
end

In my Store class app/models/store.rb:

class Store < ActiveRecord::Base
  validates_presence_of :store_name,
                        :address, 
                        :number_of_employees

  def self.import(file)
    CSV.foreach(file.path, :headers => true,
                       :header_converters => lambda { |h|     h.downcase.gsub(' ', '_')},
                       :col_sep => "\t"
                       ) do |row|
       Store.create! row.to_hash
     end
   end
end

In my model test test/models/store_test.rb:

require 'minitest/autorun'
require File.expand_path("../../test_helper", __FILE__)


require 'minitest/mock'
require 'minitest/unit'
require 'date'

Minitest.autorun
class StoreTest < Minitest::Test

  def setup
    @mock = Store.new
    @mock.store_name = "Example Store"
    @mock.address = "111 Maple St"
    @mock.number_of_employees = 5
  end

  def should_import_csv_file_with_all_fields_present
    @mock = Minitest::Mock.new
    @mock.save!
    assert_equal "Example Store", @mock.store_name
    assert @mock.verify
  end
end

running test with ruby test/models/store_test.rb returns:

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

This is a basic question but it looks as though no tests are being run. Any help is much appreciated!

How to unit test grpc-java server implementation functions?

I have an implementation of GRPC-java server code, but I didn't find the example code to unit test the StreamObserver. Does anyone know the right way to unit test the function?

public class RpcTrackDataServiceImpl implements TrackDataServiceGrpc.TrackDataService {

  @Override
  public void getTracks(
  GetTracksRequest request,
  StreamObserver<GetTracksResponse> responseObserver) {
GetTracksResponse reply = GetTracksResponse.newBuilder()
    .addTracks(TrackInfo.newBuilder()
        .setOwner("test")
        .setTrackName("test").build())
    .build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
  }
}

How to do Backbone unit testing for dom manipulation function

While clicking, the function performing dom manipulation like appending dom elements. how to do unit test for this function in mocha with help of chai & sinon js..?

ExceptionHandler for WebAPi unit test

I have a GlobalExceptionHandler which handles all the exceptions of a WebAPI in a central way. I need to add some unit tests to make sure that the exceptions catched by this class generate the Results in the correct format.

In web config, I have this : config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); which works perfectly.

I do the same thing when configuring a controller for unit test. But when calling the controller methods from unit tests, the exception is not catched by GlobalExceptionHandler. What step am I missing ?

PHPUnit API Testing GET url parameters

$response = $this->call('GET','abc?foo=bar');

I'm unable to get PHPUnit to transmit "foo" as a request variable. Any thoughts? Am I missing something?

set singleton instance to nil in my case

I am using OCMock 3 to unit test my iOS project.

I use dispatch_once() created a singleton class MyManager :

@implementation MyManager

+ (id)sharedInstance {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

I have a method in School class which uses the above singleton:

@implementation School
...
- (void) createLecture {
  MyManager *mgr = [MyManager sharedInstance];
  [mgr checkLectures];
  ...
}
@end

Now, I want to unit test this method, I use a partial mock of MyManager:

- (void) testCreateLecture {
  // create a partially mocked instance of MyManager
  id partialMockMgr = [OCMockObject partialMockForObject:[MyManager sharedInstance]];

  // run method to test
  [schoolToTest createLecture];
  ...
}

- (void)tearDown {
  // I want to set the singleton instance to nil, how to?
  [super tearDown];
}

In tearDown phase, I want to set the singleton instance to nil so that the following test case could start from clean state.

I know on internet, some people suggest to move the static MyManager *sharedMyManager outside the +(id)sharedInstance method. But I would like to ask, is there any way to set the instance to nil without moving it outside +(id)sharedInstance method?

OCMock automatically use mocked instance in code under test?

I am new in OCMock.

I use dispatch_once() created a singleton class MyManager :

@implementation MyManager

+ (id)sharedInstance {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

I have a method in School class which uses the above singleton:

@implementation School
...
- (void) createLecture {
  MyManager *mgr = [MyManager sharedInstance];
  [mgr checkLectures];
  ...
}
@end

Now, I want to unit test this method, I use a partial mock of MyManager:

- (void) testCreateLecture {
  // create a partially mocked instance of MyManager
  id partialMockMgr = [OCMockObject partialMockForObject:[MyManager sharedInstance]];

  // run method to test
  [schoolToTest createLecture];
  ...
}

I noticed that with OCMock, after I created the partial mock of my singleton MyManager instance, when run my method under test, it automatically use the partially mocked instance.

This is a bit weird to me, since in my test case above, I only created the partial mock of MyManager instance without injecting it to MyManager class,

how does OCMock automatically force the code under test use this mocked instance when [MyManager sharedInstance] is called in the code under test ? Could someone explain to me this?

robolectric runOnUiThread on a Thread does NOT work

runOnUiThread() does not seem to work when being executed within a thread. Anybody knows of a workaround?

Note: I filed a ticket here - http://ift.tt/25x4uPk

import android.app.Activity;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertTrue;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class RunOnUiThreadTest {

    /**
     * Works
     * @throws Exception
     */
    @Test
    public void inside_the_main_thread() throws Exception {
        final Activity activity = Robolectric.setupActivity(Activity.class);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean didRun = new AtomicBoolean(false);

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                didRun.set(true);
                latch.countDown();
            }
        });

        latch.await(20, TimeUnit.SECONDS);
        assertTrue(didRun.get());
    }

    /**
     * Fails
     * @throws Exception
     */
    @Test
    public void inside_a_new_thread() throws Exception {
        final Activity activity = Robolectric.setupActivity(Activity.class);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean didRun = new AtomicBoolean(false);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        didRun.set(true);
                        latch.countDown();
                    }
                });
            }
        });
        thread.start();

        latch.await(20, TimeUnit.SECONDS);
        assertTrue(didRun.get());
    }

}

Robolectric unit tests build.os version returns incorrectly?

Hi i am trying to run a unit test that executes a code block if the build version is 23 or more but when i call the Build.VERSION.SDK_INT it always returns 1?

here is the unit test code:

@Config(emulateSdk = 18)
public class Test {

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
         //test some block of code

   }

}

Mocking CountDownTimer and Handler

I'm using Mockito and PowerMockito to write my Unit Test on Android.

I've managed to work with almost all by back stuff, but I'm stuck with the CountDownTimer and Handler.

I'm able to mock a subclass of CountDownTimer, but I'm not able to mock it's final method like cancel(), so each time the cancel() method is called, the test runner report a java.lang.RuntimeException: Method cancel in android.os.CountDownTimer not mocked. See ...

Do anyone have a solution for this without using Robolectric?

how to check the return value of a function in unit test with OCMock 3

I am using OCMock 3 to do unit testing in my iOS project.

OCMock is said a great unit testing library for iOS, but the OCMock document I linked above doesn't say clearly how to check the return value of a function, it all the time says how to stub function return & verify that. But I don't want to stub that function return, I need to check the real return value.

For example, I want to unit test a function of my School class:

@implementation School
...
- (void) checkStudents {
  BOOL isOnVacation = [[Coordinator sharedInstance] checkCalendar];
  if (!isOnVacation) {
     takeLecture();
  }
}
@end 

My test case:

- (void) testCheckStudents {
    // create a partially mocked 'Coordinator' instance
    id coordinatorMock = [OCMockObject partialMockForObject:[Cooridnator sharedInstance]];

    // run the method under test
    [schoolToTest checkStudents];

    // I want to check not only '[[Coordinator sharedInstance] checkCalendar]' is invoked, but also check its return value is YES. How to check this in OCMock?
    OCMVerify([coordinatorMock checkCalendar]);
}

I don't want to stub the return value of [[Coordinator sharedInstance] checkCalendar], but run the real implementation.

I want to check not only [[Coordinator sharedInstance] checkCalendar] is invoked, but also check its return value is YES. How to check this in OCMock?

(With its documentation, I can only see stub function return here & there then verify the function is called. Do I miss something in its documentation?)

async method not returning when called from TestMethod

I am using Visual Studio 2013 and MSTest for unit testing my async method. I have async method as below:

    public async Task<Client> AddClientAsync(Client newClient)
    {
        newClient.ObjectState = ObjectState.Added;
        base.Insert(newClient);
        await unitOfWorkAsync.SaveChangesAsync();
        return newClient;
    }

I have written following unit test method to test it.

    [TestMethod]
    public async Task AddClientAsync_Success()
    {
        Client client = new Client()
        {
            Id=2,
            FirstName="John",
            LastName="Tylor",
            MaritalStatusId=1,
            RecordStatus=1                
        };

        var result = await clientAppService.AddClientAsync(client);
        Assert.IsNotNull(result);
    }

When I run/debug test case control reaches till below line and never returns. Its kind of getting stuck and keeps waiting endlessly at this line and test never completes.

await unitOfWorkAsync.SaveChangesAsync();

Any idea what am I missing here?

CMock additional include via CLI

Introducing CMock on top of Unity into our build system (based on make) I keep struggeling with the correct handing over of additional include headers to cmock. We don't want to use configuration YML files since we like to have all config stuff within our Makefiles. Thus I am stuck with handing over all configs zu the cmock ruby script when calling it by CLI arguments. This works with the mock_prefix and the mock_path. Handing over the aray containing the additional include headers fails as of now. Here's what the call within the Makefile looks like:

CMOCK_MOCKS_DIR     = $(THIS_DIR)/sr/mocks
CMOCK_MOCKS_PREFIX  = mock_
CMOCK_ARGS         += --mock_path="$(strip $(CMOCK_MOCKS_DIR))"
CMOCK_ARGS         += --mock_prefix="$(strip $(CMOCK_MOCKS_PREFIX))"
CMOCK_ARGS         += --includes="qep.h, qep_port.h, qp_port.h"

mock:
    $(Q) $(MKDIR) $(strip $(CMOCK_MOCKS_DIR))
    ruby $(strip $(CMOCK_DIR))/cmock.rb $(CMOCK_ARGS) $(MOCK_HEADERS)

Which results in this call on the shell

ruby C:/cmock/lib/cmock.rb --mock_path="C:/unittest/src/mocks" --mock_prefix="mock_" --includes="qep.h, sp_core.h, sp_osapi.h" qf.h
WARNING: :includes should be an array.

Handing over the configuration as YML works with several include headers given inside. Also configuring a single additional include header by usage of CLI also works, only passing more than one file fails. Does anybody have experience with handing over an array to cmock?

Thanks for the support!

Mockito - mock a method call in constructor

I have a class X which takes in a YBuilder and constructs an instance of Y

public class X {
  private Y y;
  public X(YBuilder builder) {
    y = builder.build();
  }
}

I need to mock all calls to Y, so I have written my Unit tests like this:

@Mock
private Y Y;

@Mock
private YBuilder builder;

@InjectMocks
private X x;

@Before
public void setup() {
  when(builder.build()).thenReturn(y); // this does not work
}

I get a Null Pointer Exception in my main class since the dependency Y has not been mocked.

I think this is due to the fact that @InjectMocks instantiates a new instance of X before I am able to mock the call.

How can I fix this? Any inputs are appreciated.

Ignore parent class' method in unit testing with mockito

I have the following class which I try to test:

public class ClassA extends ClassB {
  ...
  public String methodToBeTested(){
    methodA1();
    methodB();
    return something;
  }
  ...
}

The methodB is parent class's method. I want to ignore this method or just stub it. I'm trying the following more and less:

public class TestClassA{
  @Mock
  ClassB instanceB;

  public String testTheMethodToBeTested{
    doNothing().when(instanceB).methodB();
    ClassA instanceA = new ClassA();
    String result = instanceA.methodToBeTested();
    String expected = "foo"
    assertTrue(result.equals(expected));
  }
  ...
}

However I see that methodB still is being executed. However in ClassA if I declare a classB variable and it's setter; and instead of methodB() write classB.methodB() my tests executes. But I am asked to not change the code being tested. Is there any way to test ClassA ?

How to Configure Cobertura with testNG in Ant

Here is my build xml. After I run the target "coverage-test", in command line it displays that the test is passed. Then "cobertura.reports" target is run. But coverage tool report displays no test coverage. What should i do to solve the problem. Can any one explain how to properly configure testNG and Cobertura, in Ant target ?

 <project basedir=".">

    <property name="src.dir" value="${basedir}/src"/>
    <property name="lib.dir" value="${basedir}/lib"/>
    <property name="build" value="${basedir}/build"/>
    <property name="tng.conf.dir" value="${src.dir}/conf"/>
    <property name="cobertura.dir" value="${lib.dir}/cobertura" />
    <property name="coverage-output" value="${basedir}/coverage-output" />
    <property name="reports" value="${basedir}/reports" />


    <taskdef name="testng" classname="org.testng.TestNGAntTask">
        <classpath>
            <pathelement location="lib/testng-6.8.jar"/>
        </classpath>
    </taskdef>

    <path id="class_path">
        <pathelement path="${build}"/>
        <fileset dir="${lib.dir}">
            <include name="**/*.jar"/>
        </fileset>
    </path>

    <path id="cobertura.classpath">
        <fileset dir="${cobertura.dir}">
            <include name="cobertura-1.9.4.1.jar" />
            <include name="log4j-1.2.17.jar"/>
            <include name="asm-3.1.jar"/>
            <include name="asm-tree-3.0.jar"/>
            <include name="jakarta-oro.jar"/>
            <include name="lib/**/*.jar"/></fileset>
    </path>

    <taskdef classpathref="cobertura.classpath" resource="tasks.properties" />


    <!--<cobertura-instrument todir="${instrumented.dir}">-->
        <!--<ignore regex="org.apache.log4j.*" />-->
        <!--<fileset dir="${build}">-->
            <!--<include name="**/*.class" />-->
            <!--<exclude name="**/*Test.class" />-->
        <!--</fileset>-->
    <!--</cobertura-instrument>-->

    <target name="clean" description="Clear previous build class files">
        <delete dir="${build}" quiet="true"></delete>
        <delete file="cobertura.ser" />
        <delete dir="${coverage-output}" quiet="true"></delete>
        <delete dir="${reports}" quiet="true"></delete>

        <!--<delete dir="${coverage-output}/" />-->
    </target>


    <target name="compile" description="compile java class">
        <mkdir dir="${build}"/>
        <mkdir dir="${coverage-output}"/>
        <mkdir dir="${reports}"/>
        <javac srcdir="${src.dir}" destdir="${build}" debug="yes">
            <classpath refid="class_path"></classpath>
        </javac>

        <copy todir="${build}">
            <fileset dir="${src.dir}">
                <include name="**/*.xml"/>
                <include name="**/*.properties"/>
            </fileset>
        </copy>
    </target>

    <!--<target name="ng-test" description="Check very specific test ng target only">-->
        <!--<testng classpathref="class_path" groups="test-fl-one">-->
            <!--<classfileset dir="${build}" includes="**/*Test.class"></classfileset>-->
        <!--</testng>-->
    <!--</target>-->
    <!---->
    <!--<target name="test-by-xml" description="Check by Testng xml" depends="cobertura" >-->
        <!--<testng classpathref="class_path" outputdir="${build}" haltonfailure="false">-->
            <!--<classpath location="${build}"></classpath>-->
            <!--<xmlfileset dir="${tng.conf.dir}" includes="testng.xml"/>-->
        <!--</testng>-->
    <!--</target>-->

    <target name="cobertura" depends="compile">

        <cobertura-instrument todir="${coverage-output}">

            <fileset dir="${build}">
                <include name="**/*.class" />
                <!--<exclude name="test/*.class"/>-->
            </fileset>
        </cobertura-instrument>
    </target>

    <target name="coverage-test" depends="cobertura">
        <testng classpathref="class_path" groups="test-fl-one">
            <classfileset dir="${coverage-output}" includes="test/*.class" />
        </testng>
    </target>

    <target name="cobertura.reports">
        <cobertura-report format="html" srcdir="${build}" destdir="${reports}" />
    </target>

</project>

Django unit testing - assertRaises working when it shouldn't

I was code reviewing an API and I found this in a unit test. The test passes but I can't understand why.

class SomeTestCase(TestCase):

    def setUp(self):
        self.client = Client()

    @mock.patch("patch.a.thing", mock_function)
    def test_fail(self):
        request_data = {
            "some": "bad data"
        }

        response = self.client.post(
            "/path/to/api",
            json.dumps(request_data),
            content_type="application/json",
            HTTP_HEADERNAME=HEADER_VALUE
        )

        self.assertRaises(Exception, response)

We're expecting a 500 status code from the API as we're passing in bad data. Even if calling the API were to cause an exception, would that not be raise during the client.post casing the unit test to error? response is not a callable and therefore it is wrong to pass it to assertRaises, however the behaviour I would expect to see is that assertRaises does not get an exception and therefore the unit test fails. Can anyone explain why it behaves this way?

Auto generated test case failing in netbeans

I have a Calculator class which has a method to add two numbers.

public class Calc {
    public int add(int a, int b){
        return a+b;
    }
}

I created its Test class using netbeans context menu Tools->create tests which is failing. I can't figure out why.

@Test
public void testAdd() {
    System.out.println("add");
    int a = 0;
    int b = 0;
    Calc instance = new Calc();
    int expResult = 0;
    int result = instance.add(a, b);
    assertEquals(expResult, result);
}

Karma-jasmine UncaughtReference Error Statusbar not defined

I have strange occurence when testing my hybrid application build with cordova and ionic.

I use karma-jasmine for the unit-testing. If I run my test files sparately they succeed. If I run 3 of them together, they still succeed. If include all of them in karma (path/tests/*.js) 3 out of 5 succeed and following error occurs: "StatusBar" is not defined.

StatusBar is the cordova plugsin "cordova-plugin-statusbar". I wonder why it only appears when testing all files together and not one by one. I already tried to reorder the testfiles, but they always failed after the third testfile.

Everytime a test is fired, the app.js is initialized and started. I don't know if this may be a problem.

Any suggestions?

How to cover image conversion in a C# unit test?

We've written a library that generates thumbnails for various file formats. I like to unit test this library. It generates JPEG files.

How would I unit test an image conversion? How can I check if two images look alike when JPG uses a lossy format?

Microsoft TestTools has an ImageCompare class, but I'm not sure if it fits my profile. Any ideas?

How can I migrate my custom matchers from Jasmine 1 to Jasmine 2

Version 2 of the JavaScript testing framework jasmine unfortunately introduced several breaking changes. One of these changes is the way custom matchers are handled, as is outlined here:

http://ift.tt/1tEVMxw

The addMatchers function is no longer on the spec (this) it is now on the global jasmine object.

 /* was:
     this.addMatchers({
  */
  jasmine.addMatchers({

A matcher is set up a bit different now. The factory receives a util object which contains things like jasmines equality functions, and any registered customEqualityTesters. The factory is expected to return an object with a compare function which will be called with the actual and expected directly, instead of the actual value being on this

   /* was:
       toBeCustom: function(expected) {
         var passed = this.actual == expected;
    */
    toBeCustom: function(util, customEqualityTesters) {
      return {
        compare: function(actual, expected) {
          var passed = actual == expected

The comparison should now return an object with pass and message attributes.

I am looking for an easy way to migrate our existing matchers, so that we can easily switch to the new jasmine version.

Right Click in Visual Studio 2013 not showin create unit test

Right Click (which shows Context Menu) doesn't show Create Unit Test. I tried this, but it fails:

Options in my VS doesn't show Create Unit Test as well.

Have you guys got any idea what I can do?

P.S. I have Visual Studio Professional 2013.

lundi 30 mai 2016

Web api Unit testing for required fields present in json response

One of my .Net web api endpoint returns a JSON object of following structre

    public class UserModel
    {
        public int StudentID { get; set; }
        public int ClassID { get; set; }
        public string ClassName { get; set; }
        public int TestLevelID { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Email { get; set; }        
        public int? Active { get; set; }
        public string Displayname { get
            {
                return Firstname + " " + Lastname;
            }
        }
        public List<TestSummary> CourseSummary { get; set; }
    }

    public class TestSummary
    {
        public string Coursename { get; set; }
        public int Progressvalue { get; set; }
    }

How to implement the unit Test method in a way that checks for all properties are correct ? Required fields contain non-null data and optional field contains at least null

    [TestMethod]
    public void GetStudent()
    {
        var service = new StudentDbHandler();
        var students = service.GetStudents(1).ToList();
        bool _exists = false;
        if (students.Count > 0)
        {
            _exists = true;
        }
        Assert.IsTrue(_exists);
        //now checls first name is not null
        Assert.IsNotNull(students.FirstOrDefault().Firstname);
    }

So should i do this for all properties or is any easier way

How to mock React Native component in testing?

During testing React Native projects I got errors on requireing native components. How would you solve this problem?

How to get a unittest.mock.sentinel act as a string instance?

I am writing some unit tests for a library which populates data from a dictionary.

I want to check that the populated data is correct according to the dictionary, and I use sentinels to identify the data.

However, the library is written with a check that the parameter is an instance of a string (isinstance(foo, str)), and the sentinel obviously doesn't pass this test.

Is there a way to get the sentinel be considered as an instance of a string? I already tried unittest.mock.sentinel.foo.__class__ = str, but these objects don't work as well as mocks.

Unittest - Test for dict equality

I am trying to do a unit-test but don't quite get why these 2 dicts show up as not equal. I was wondering if someone could give me an explanation for this occurrence. My code is...

import unittest

class TestEmailValidator(unittest.TestCase):

    def test(self):
        known_dict = {
            'debo@foobar.com': True,
            'debo@gmail.com': False
        }

        result_dict = {}

        for key in known_dict.keys():
            result_dict[key] = is_email_valid(key)

        # debugger results
        # result_dict = {
        #    'debo@foobar.com': True,
        #    'debo@gmail.com': False
        # }

        if self.assertEqual(known_dict, result_dict):
            print "is_email_valid passed"
        else:
            print "is_email_valid failed"

if __name__ == '__main__':
    unittest.main()

I get the same result for assertEqual, assertEquals and assertDictEquals. I have tried assigning result_dict to known_dict before the test, but that did not pass either.

It would be great if someone could point me to why this could be happening. Thanks for reading. :)

C# Controller unit tests failing with bad image format exception, when referenced to service project

C# Controller unit tests failing with the below bad image format exception, when referenced to service project. Both the service and unit test project are being built as AnyCpu. Any suggestions on how to fix this exceptions?

Test method UnitTests.Controller.SomeControllerTests.SampleTest threw exception:

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

Evosuite: failure in executing test cases

I follow the evosuite maven documentation to generate unit test cases for my project. Below is the command I've used:

mvn -DmemoryInMB=2000 -Dcores=2 evosuite:generate evosuite:export  test

The tool takes around 1 hour to generate test cases for my project (with 9700 lines of Java code). However when it proceed to mvn test phase, all test cases failed with the same message:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec <<< FAILURE! - in com.xxx.yyy.util.Messages_ESTest
com.xxx.yyy.util.Messages_ESTest  Time elapsed: 0 sec  <<< ERROR!
java.lang.IllegalStateException: Trying to set up the sandbox while executing a test case
    at <evosuite>.<evosuite>(<evosuite>)
    at <evosuite>.<evosuite>(<evosuite>)
    at <evosuite>.<evosuite>(<evosuite>)

While running the generated test case in Intellij IDEA most of them can pass the test:

enter image description here

Any one got any idea?

VS 2015 Debug method being tested

I'm developing a unit test, and I'm getting a null ref exception. I would like to debug not only the code of the test, but the real method being tested... how can i do that?
right now, if I F11 the method, i just get the exception...

Unit Test Fails due to uninitialized static property

I have a static method in a static class that fails under unit testing. The problem is that it requires the value of a public static property from a different static class. The value of the property in the unit test is always null because the source class is not initialized. Both static classes are in the same project. If I execute the method directly, I get the desired results, but I am unable to use a test.

Static Class A:

static class App {

  private static string appDir;

  public static string AppDir => appDir;

  [STAThread]
  static void Main() {

    appDir = AppDomain.CurrentDomain.BaseDirectory;

    DbEng.PutIdbVal("x", "Y");  // Method under test - Works here

  }
}

Static Class B:

public static class DbEng {

  private static SQLiteConnection idbCn = new SQLiteConnection("Data Source=" + AppDir + "gcg.idb"); // AppDir is valid when not testing, is null when testing.

  public static void PutIdbVal(string key, string value) {

  using (var cmd = new SQLiteCommand("INSERT INTO tKv (Key, Value) VALUES (@key, @value)", idbCn)) {
      cmd.Parameters.Add(new SQLiteParameter("@key", key));
      cmd.Parameters.Add(new SQLiteParameter("@value", value));
      idbCn.Open();
      cmd.ExecuteNonQuery();
      idbCn.Close();
    }
  }
}

Unit Test:

[TestClass]
public class DbEng_Tests {
  [TestMethod]
  public void PutIdbVal_Test() {

    string TestKey = "Test-Key";
    string TestValue = "Test - Value";

    DbEng.PutIdbVal(TestKey, TestValue);

  }
}

Is it possible to force the unit testing code to initialize static class A before calling the method in static class B?

Mock objects Vs Real objects

  • In Unit testing, why do we use mock objects?

  • How are mock objects better than real objects in unit testing?

  • When you create a mock object, what exactly it means? For example let's say you create

    A a = Mockito.mock(A.class);

    Does it create an object of class A? or something else?

  • When you create a mocked object and use it in calling a method, say a.method1(), how does the mocked object knows that it should call method1 itself?

Kindly let me know about these.

addCleanUp vs tearDown

Recently, Ned Batchelder during his talk at PyCon 2016 noted:

If you are using unittest to write your tests, definitely use addCleanup, it's much better than tearDown.

Up until now, I've never used addCleanUp() and got used to setUp()/tearDown() pair of methods for test "set up" and "tear down" phases.

Why should I switch to addCleanUp() instead of tearDown()?

how to mock private static inner class?

I have a class like

public class Enclosing {

   public String methodA() {
     Inner.getContext();
     ......
   }

   private static class Inner{
     // some context init
     public Context getContext() {
       .....
     }
   }
}

Now I want to test methodA without invoking the real Inner.getContext(). I have been searching all over but cannot find a working solution. I am using Java 8. Can I have some help please? Many thanks

How to unit test Neo4j with Scala?

I need to test some Neo4J queries in my unit/integration tests with Scala.

Is there any way to do it? the only solution is Neo4j embbeded?

Mocking dependencies that use protocol extensions does not call the mock method

I have an issue where I am trying to test a class that has two dependencies. The dependencies implement a protocol, and I pass two 'mock' objects that also implement the protocol(s) to my object under test. I have reproduced the problem in a small test app below.

import UIKit

// first dependency of `Data` (below)
protocol Local {}
extension Local {
    // the default method that I want my app to use when running a
    // `normal` execution mode, i.e. not a test
    func isCached (url : NSURL) -> Bool {
        return true
    }
}

// the actual class definition that the app normally runs
class LocalImpl : Local {}

// much the same as `Local` above
protocol Server {}
extension Server {
    func getURL (url : NSURL) -> NSData? {
        // todo
        return nil
    }
}
class ServerImpl : Server {}

// The object that I want to test.
protocol Data {
    var local : Local { get set }
    var server : Server { get set }
}
extension Data {

    func getData (url : NSURL) -> NSData? {
        if local.isCached(url) {
            return nil
        } else {
            return server.getURL(url)
        }
    }
}
class DataImpl : Data {
    var local : Local
    var server : Server

    init () {
        local = LocalImpl()
        server = ServerImpl()
    }

    init (server : Server, local : Local) {
        self.server = server
        self.local = local
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let data : Data = DataImpl()
        data.getData(NSURL(string: "http://google.com")!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Then, in my test

@testable import TestingTests

class Test: XCTestCase {

    // the mock server instance I want to use in my test
    class MockServer : Server {
        static var wasCalled = false
        func getURL(url: NSURL) -> NSData? {
            MockServer.wasCalled = true
            return nil
        }
    }

    // the local instance I want to use in my test (with overridden protocol function)
    class MockLocal : Local {
        func isCached (url : NSURL) -> Bool {
            return false
        }
    }

    func testExample() {
        let data = DataImpl(server: MockServer(), local: MockLocal())
        data.getData(NSURL(string: "http://hi.com")!)
        XCTAssert(MockServer.wasCalled == true)
    }
}

The above test will fail. When stepping through the test with a debugger, the protocol definition of isCached will be called on the Local object. In other words, the "default" implementation runs instead of the one that I defined in my test.

If I set breakpoints in my test file, the Data object is set up properly and has my mocks set. However, once I step into the getData function, trying to print out data.local or data.server from LLDB will produce bad access errors (app doesn't actually crash, but the debugger cannot print the value)

Am I missing something here, or can someone explain to me why you cannot do this?

Running Xcode 7.3.1 with Swift 2

django unittest import error

Microsoft Windows [Version 6.0.6002] Copyright (c) 2006 Microsoft Corporation. All rights reserved.

C:\Users\mech10>cd superlists

C:\Users\mech10\superlists>python manage.py test
Creating test database for alias 'default'...

E

ERROR: lists.tests (unittest.loader._FailedTest)

ImportError: Failed to import test module: lists.tests
Traceback (most recent call last):
File "C:\Users\mech10\Anaconda3\lib\unittest\loader.py", line 428,in    _find_test_path
module = self._get_module_from_name(name)
File "C:\Users\mech10\Anaconda3\lib\unittest\loader.py", line 369, in _get_module_from_name__import__(name)
File "C:\Users\mech10\superlists\lists\tests.py", line 9
self.assertEqual(found.func,home_page)
                                     ^
TabError: inconsistent use of tabs and spaces in indentation


Ran 1 test in 0.001s

FAILED (errors=1)
Destroying test database for alias 'default'...

tests.py

    from django.core.urlresolvers import resolve
    from django.test import TestCase
    from lists.views import home_page


    class HomePageTest(TestCase):
      def test_root_url_resolves_to_home_page_view(self):
        found = resolve('/')
        self.assertEqual(found.func,home_page)

urls.py

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^$', 'lists.views.home_page', name='home'),
]

views.py

from django.shortcuts import render

def home_page():
  pass

I want to follow the instructions from a django test book but I could not understand my test script did not work.

Spring Boot MongoRepository unit testing using pre-installed MongoDB

I have a regular Spring Boot application (1.3.2) with MongoDB using MongoRepository.

I would like to write an integration test for one of my endpoints that gets the data from the MongoDB. As far as I see from the Spring Boot 1.3 Release Notes Spring has auto-configuration for Embedded MongoDB (de.flapdoodle.embed.mongo). However, I cannot figure out from Spring and flapdoodle documentation on how to write an integration test that would use already installed version of MongoDB on my filesystem.

So far my integration test looks like this:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(Application.class) // my application class
@WebAppConfiguration
public class IntegrationTest {

    @Autowired
    private MyRepository myRepository;

    @Before
    public void setup() {
        myRepository.save(new MyEntity());
    }

    @Test
    public void test() {
        // here I will fire requests against the endpoint
    }
}

I have added two dependencies with test scope: spring-boot-starter-test and de.flapdoodle.embed:de.flapdoodle.embed.mongo. So when I run the test, I can see that flapdoodle attempts to download version of MongoDB, but fails since I am behind the proxy. But I do not want to download any versions, I want it to use my locally installed MongoDB. Is it possible to do this?

How to write unit tests for server side Meteor code?

I have some server side code -- meteor methods and simple backend helpers -- that I would like to test. I've read the documentation testing with Meteor, but I am having a hard time connecting the documentation to my very simple use case. Can someone share with me how they've tested a meteor method or a simple backend JS function?

For instance, let's say you have some server method in, some_methods.js

function someHelper() {
// does lots of cool stuff
};

Meteor.methods({
  'user/update' (userProperties) {
     // updating some user properties
   }
})

Risk based static analysis tools - different rules for components?

We have quite a large project where and tend to apply risk based approach to stringency of unit tests and code reviews. E.g. components classified as A need to have higher coverage than components classified as B. However, it is nearly impossible without a support of static analyser - is there a way how to instruct (e.g. Sonar) to apply different rules on different modules?

Testing element.bind('error')

Trying to figure out how to test this directive, but when I log out element I just keep getting this.

Object{0: <img ng-src="img/img.jpg" err-src="img/err.png" src="img/img.jpg">, length: 1}

How would I test this with different http codes to make sure my directive is working properly?

directive.js

.directive('errSrc', function() {
  return {
    link: function(scope, element, attrs) {

      scope.$watch(function() {
        return attrs.ngSrc;
      }, function (value) {
        if (!value) {
          element.attr('src', attrs.errSrc);
        }
      });

      element.bind('error', function() {
        element.attr('src', attrs.errSrc);
      });
    }
  };
})

test.js

describe("Directives", function () {


    describe("err-src Directive", function () {


        var element, $scope;
        beforeEach(module('app'));

        beforeEach(inject(function ($compile, _$rootScope_, _$httpBackend_) {

            $scope = _$rootScope_.$new();
            $httpBackend = _$httpBackend_;

            element = angular.element('<img ng-src="img/img.jpg" err-src="img/err.png">');

            element = $compile(element)($scope);

            $scope.$digest();
            console.log(element);

        }));

        it("Should replace src with err icon if 404", function () {
            $httpBackend
                    .when('GET', 'img/img.jpg')
                    .respond(404);
        });
        it("Should replace src ng-src if 200", function () {
            $httpBackend
                    .when('GET', 'img/img.jpg')
                    .respond(200);


        });
    });
});

What would be better to add Unit test to: Manager, controller, DAL?

we have an architecture with Controller, Manager (for BL) and a Data Access Layer

Where would it be better to add our Unit Testing. Something tells me that the manager is the best place, because logic will be stored there.

Another idea is that if we test the controller it's more complete (but it sounds too wide in some cases a lot of functionallity would be tested )

And the DAL sounds like THE most atomic part to test, but we are not testing the real outcome. BR

MG

Promise.resolve().then not working in jasmine test

I'm trying to setup a test which involves promises. Here is my example code:

var promise;

beforeEach(inject(function ($q) {
    promise = $q.resolve();
}));

it('should resolve', function (done) {
    promise.then(function () {
        expect(true).toBeTruthy();
        done();
    });
});

DEMO

For some reason, when I run this, I get a TIMEOUT

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Why doesn't the promise execute the callback given to then ?

Cheers

How to test FacesContext showing a message with JUnit

abort()-Method:

public void abort() {
    LOG.info("some-text");
    warning("some-text");
}

warning()-Method:

 public void warning(String message) {
    FacesContext.getCurrentInstance()
.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "INFO:", message));
}

I want to write a Test-Case for abort wich is just verifying that nothing has changed and a second Test-Case which is verifying that warning() is working. I´m knowing this little two methods doesn´t need a Unit-Test but I want to know if it´s possible. UI-Test for showing the p:message is working well but I want to check the Caption, Typ and Message by Unittest before because it´s running much faster.

Trouble setting up App Engine testing environment

I am trying to unit test my app engine endpoint api. I am following the example from udacity. They seem to be using a LocalServiceTestHelper but I struggle to understand why, since it is not used later in the code.

Here is my backend gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.28'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.28'
  compile 'com.google.appengine:appengine-endpoints:1.9.28'
  compile 'com.google.appengine:appengine-endpoints-deps:1.9.28'
  compile 'javax.servlet:servlet-api:2.5'
    compile 'com.googlecode.objectify:objectify:5.0.3'
    compile 'javax.jdo:jdo-api:3.0.1'
    compile 'junit:junit:4.12'
    compile 'com.google.appengine:appengine-testing:1.9.24'
}

appengine {
  downloadSdk = true
  appcfg {
    oauth2 = true
  }
  endpoints {
    getClientLibsOnBuild = true
    getDiscoveryDocsOnBuild = true
  }
}

Here is the Endpoint test class (the import statements and other trivial details have been omitted for conciseness):

private final LocalServiceTestHelper helper =
            new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
                    .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));

    /**
     * Set up the local service tester before running tests and an instance of the magpieApi.
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        //helper.setUp();
        user = new User(EMAIL, "gmail.com" ,USER_ID);
        magpieApi = new MagpieEndpoint();
    }

    /**
     * After running tests clear objectify and tear down the local test helper.
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        ofy().clear();
        helper.tearDown();
    }

Here is important part of the error log:

java.lang.NoClassDefFoundError: com/google/appengine/api/datastore/dev/LocalDatastoreService$AutoIdAllocationPolicy

    at com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig.<init>(LocalDatastoreServiceTestConfig.java:24)
    at test.MagpieEndpointTest.<init>(MagpieEndpointTest.java:54)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    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:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.ClassNotFoundException: com.google.appengine.api.datastore.dev.LocalDatastoreService$AutoIdAllocationPolicy

I am new to google app engine and have never unit tested my code before, so please be nice (only 16 years old). There are no syntax errors so I am curious as to what is causing the issue. Line 54 is obviously the source of the problem, which is where I initiate and declare the helper variable.

Thank you.

JUnit exceptions handling testing

I am trying to test the next exception, but I don't know how to throw the exception from JUnit, because is a internal exception of the method.

public boolean suscribirADato(int idDato) {
        InetAddress ip = null;
        boolean adecuadamenteSuscrito = false;

        try {
            ip = InetAddress.getByName(ipMulticast.get(idDato));
            grupoMulticast.set(idDato, ip);
            conexion.joinGroup(grupoMulticast.get(idDato));
            adecuadamenteSuscrito = true;
        } catch (IOException e) {
            LOGGER.info(e.getMessage());
        }
        return adecuadamenteSuscrito;
    }

How to use files in instrumented unit tests

I've got this project which processes images. The library I use to do most of the actual image processing requires met to run these tests on a Android device or emulator. I'd like to provide a few test images which it should process, the thing is that I don't know how to include these files in the androidTest APK. I could supply the images through the context/resources but I'd rather not pollute my projects resources. Any suggestions as to how to supply and use files in instrumented unit tests?

Owin TestServer logs multiple times while testing - how can I fix this?

I'm trying to write unit tests for an OWIN service, but any log statements in my tests start duplicating once I run the tests all at once and really make the log output on the build server useless due to all the noise. I've distilled the problem down to a very simple repro:

[TestFixture]
public class ServerTest
{
    [Test]
    public void LogOnce()
    {
        using (TestServer.Create(app => { }))
        {
            Debug.WriteLine("Log once");
        }
    }

    [Test]
    public void LogTwice()
    {
        using (TestServer.Create(app => { }))
        {
            Debug.WriteLine("Log twice");
        }
    }
}

If I run one test at a time I get the expected output:

=> ServerTest.LogOnce
Log once

=> ServerTest.LogTwice
Log twice

If I run the tests all at once I get:

=> ServerTest.LogOnce
Log once

=> ServerTest.LogTwice
Log twice
Log twice

Initializing the TestServer once will solve the problem, but I am looking for a solution that allows me to continue instantiating as many TestServer instances as I choose.

stub function is not working in my test case

I am using OCMock 3 to write my unite tests in iOS project.

I have a foo method under School class:

@implementation School
-(NSString *)foo:
{
    // I need to mock this MyService instance in my test
    MyService *service = [[MyService alloc] init];

    // I need to stub the function return for [service getStudent]
    Student *student = [service getStudent];
    if (student.age == 12) {
       //log the age is 12
    } else {
      //log the age is not 12
    }
    ...
}

In my test case, I want to stub the method call [service getStudent] to return a Student instance with age value 12 I defined:

// create a student instance (with age=12) which I want to return by function '-(Student*) getStudent:'
Student *myStudent = [[Student alloc] init];
myStudent.age = 12;

// use mocked service
id mockService = OCMClassMock([MyService class]);
OCMStub([[mockService alloc] init]).andReturn(mockService);

// stub function return on mocked service
OCMStub([mockService getStudent]).andReturn(myStudent);

// execute foo method
id schoolToTest = [OCMockObject partialMockForObject:[[School alloc] init]];
[schoolToTest foo];

When I run my test case, however, the student returned by -(Student*)getStudent: method is not with age 12, why?

spring-boot & junit: how to mock CRUD repositories when using @ComponentScan?

I'm trying to junit test a spring boot application. For this question, I have created a simple example that serves to illustrate my issue.

A service bean:

@Service
public class DummyService {
    public String dummyMethod(String str) {
        return "Dummy(" + str + ")";
    }
}

an entity class:

@Entity
public class KeyValue {

    @Id
    @GeneratedValue
    Long id;

    @Column(nullable = false)
    String key;

    @Column(nullable = false)
    String value;
}

and a repository:

public interface KeyValueRepository extends CrudRepository<KeyValue, Long>
{
}

All of these are @Autowired into a controller.

For Unit testing, I have created a Configuration class:

@Configuration
public class MyTestConfig {

    @Bean
    public DummyService dummyService() {
        return new DummyService();
    }

    @Bean
    public KeyValueRepository keyValueRepository() {
        return  Mockito.mock(KeyValueRepository.class);
    }
}

If I test it now, it works just perfect:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyTestConfig.class)
public class UsingMockTest {

    @Autowired
    KeyValueRepository keyValueRepository;

    @Test
    public void respositoryIsMock()
    {
        MockUtil mo = new MockUtil();
        assertTrue(mo.isMock(keyValueRepository));
    }
}

This gives me a mocked version of the repository, as expected.

However, it turns out that this approach is not suitable for a larger application. Our real application contains 50+ beans which are all autowired. So what I would like to do is to @ComponentScan the application and then, in my configuration only override the beans I'd actually want to mock.

However, if I set up the test configuration like this:

@Configuration
@ComponentScan(
        basePackages = {"com.example"}
)
public class MyTestConfig {

    @Bean
    public DummyService thisForThatService() {
        return new DummyService();
    }

    @Bean
    public KeyValueRepository sayingRepository() {
        return Mockito.mock(KeyValueRepository.class);
    }
}

I will get a failed test because the repository is no longer a mock object. When I look at the spring boot log, I see the following:

2016-05-30 15:36:50.539  INFO 5908 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dummyService' with a different definition: replacing [Generic bean: class [com.example.DummyService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\work\dev\testDemo\build\classes\main\com\example\DummyService.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=myTestConfig; factoryMethodName=dummyService; initMethodName=null; destroyMethodName=(inferred); defined in com.example.MyTestConfig]
2016-05-30 15:36:50.658  INFO 5908 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'keyValueRepository' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=myTestConfig; factoryMethodName=keyValueRepository; initMethodName=null; destroyMethodName=(inferred); defined in com.example.MyTestConfig] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]

So, for the simple "DummyBean", the scanned configuration is overridden by my explicit configuration in the MyTestConfig class (which is exactly what I want), but for the CRUD Repository, the mock bean from the MyTestConfig class is overridden by the component-scanned JPA bean.

How do I avoid this behaviour in order to be able to inject @Autowired mock CRUD repositories?

Any help is greatly appreciated!

utest and haxe: run one test case many times

This question is about Haxe language. I would like to use utest to run test classes. (http://ift.tt/1cvaGkt) I need to run each test case 1000 times.

code :

for (i in 0...1000)
runner.addCase(ts);
end for

This code raises an exception:

Exception in thread "main" Haxe Exception: invalid duplicated fixture result

Is it possible to run test cases many times using utest in Haxe?

Thank you in advance

best regards.

which is the best python framework concept? for unitesting - change only config

i'm a tester; not a programmer :) i'm trying to make a python framework with which you can run any created test according to it's config.

the dir structure:

project
\runtest.py
\lib\__init__.py
\lib\cfg_parser.py
\lib\cli.py
\lib\main.py
\testscripts\__init__.py
\testscripts\test1.py
\testscripts\default.cfg

runtest.py > is ment to be a option parser:

python runtest.py --path <test path> --test <test name without .py>

(cfg name should be always default.cfg)

from unittest import TestCase,TestLoader,TextTestRunner
path_files=options.path_files
file_test=options.file_test

exec("suite = TestLoader().loadTestsFromTestCase(%s.%s)" %(file_test,file_test))
TextTestRunner(verbosity=2).run(suite)

test1.py > use to run steps defined using values from dictionaries created from config using config_parser

from unittest import TestCase,TestLoader,TextTestRunner
from lib.cfg_parser import *

class TestScript(TestCase):
    def step1...

default.cfg >

[DEVICE1]
ip_ts = 192.168.0.2
port_ts = 6046
user=admin
pass=admin

cfg_parser.py > used to create global dictionaries >>> just call DEVICE1['ip_ts'] for ip for example

from ConfigParser import SafeConfigParser
from main import file_cfg >>> file_cfg should have path+default.cfg

def cfg_parser(file):
    parser = SafeConfigParser()
    parser.read(file)

    list_dict=[]
    list_sut=[]

    for sut_name in parser.sections():
        list_sut.append(sut_name)
        dictt={}
        for name, value in parser.items(sut_name):
            dictt[name] = value 
        globals()[sut_name]=dictt

        list_dict.append(globals()[sut_name])
    return (list_sut, list_dict)

list_sut, list_dict = cfg_parser(file_cfg)
for element in list_sut:
    j=list_sut.index(element)
    exec("global %s" %element)
    exec("%s = %s" %(element,list_dict[j]))

cli.py >>> class with methods used to reach de device via serial/telnet etc.

main.py >>> should be used to store path, test, config name etc. so can be runned by test1.py,cfg_parser.py and all scripts with init.py created in its dir

i'm stumped at>

  1. how to pass from runtest.py the variables introduced by the user to main.py so they can reach cfg_parser and test1? (test1 needs cfg data to be ran)
  2. i observed that if i change the python path... the created modules/methods are no longer recognized.... how could I fix this?

hope i was clear enough :d

my logic is:

  1. i ran runtest.py and give options: --path /project/testscripts/ --test test1 later i wanna make options for os (linux/windows)
  2. test1.py should be ran with the values from default.cfg
  3. values should be obtained with cfg_parser help

any help about the flaws/mistakes of my concept is greatly appreciated

thank you :)

I am Getting error when i am testing the controller with the Nock

Hi i want to mock the controller function using the npm Nock module. I am Getting the error as Cannot read property 'json' of undefined. Here My code is

branchController.js:

exports.create = function (req, res) {
    var branch = new branch(req.body);

    Branch.save(function (err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(branch);
        }
    });
};

branchtest.js

describe('Branch Controller Testing', function () {
    it('should create a new Branch', function (done) {
        nock('http://localhost:4000',{
        },options)
            .matchHeader('accept', 'application/json')
            .post('/api/branch', {
                street1: 'Unforgiven II'
            })
            .reply(200, {'Content-Type': 'application/json'});
            branch.create(function(error, response) {
            expect(response).to.eql('OK')
            done()
        })

    })
})

Please can anybody help me on this issue.

Simulating users logged in via CAS in testng tests

We are writing unit tests for our java apis using RESTEasy Server Side Mock Framework. As part of the tests, we also need to simulate user login. Some parts have to be done by user1, followed by user2 and then user1 again.

In the actual application, the login is handled via CAS server, ie the cas web server is available.

In the tests, we are able to mock the RESTEasy services using the mock framework. The cas login REST api's are documented, but they would be part of a separate webapp and not the business webapp that involves user 1 and user 2.

How do we mock the CAS login services without having to bring up the cas server during unit testing?

If the question is not clear please let me know and I can add more details.

Using Server.Mappath in a Unit Testing project

I am planning to write unit test for a web api function which is using a line of code to load XML file using Server.MapPath

While running from UnitTest project same returns null to me .

One solution to this issue is pass filename to the function from the controller So i can use Context.Current,Server.MapPath while running the web api project and while running from unit test i can use a hardcoded file path,

Is there any other way so that i can use the same line of code for both UnitTest and actual Web api endpoint call

Django testing file field with upload_to function

I have a Django model that uses a file field and I am using an upload_to function during its instantiation to prevent name conflicts in the storage directory.

Eg:

# defined in app.models
class ABC(models.Model):
   image = models.ImageField(upload_to=UploadToPathAndRename('images'))

# defined in app.utils
@deconstructible
class UploadToPathAndRename(object):

    def __init__(self, path):
        self.sub_path = path

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(self.sub_path, filename)

I was testing the function as follows

def test_ABC(self, mock_utils):
    with open('app/tests/testimage.png') as image:
        response = self.client.post(reverse('url'),
                            {'id': id, 'image': image})
        self.assertRedirects(response, "expected_url")

But this creates a copy of the image in the images directory. I can't pass a SimpleUploadedFile as Pillow throws an error saying the uploaded image is invalid.

Can someone please show me how to mock the UploadToPathAndRename class so that it becomes easier to test the above code. Thanks.

Why doesn't Pythons unittest.assertRaises() raise an error here?

Using Python 3.5, why does all tests below pass when run? Since, an Exception is not raised when div is called, how come that assertRaises() doesn't complain?

According to the documentation for assertRaises(): "or fails if no exception is raised".

Can someone help me out?

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s




def div(self, x, y):
    if y == 0:
        raise Exception("Division by zero")
    return x / y

class MyTest(unittest.TestCase):

    def test1(self):
        with self.assertRaises(Exception) as cm:
            self.div(2, 1)

    def test2(self):
        self.assertRaises(Exception, div, 2, 1)

Use database connection to Unit testing project

How to use database connection with our Unit testing project. We have some thousands of unit test code that follows NUnit framework for our MVC application. We have lot of business logic codes that connect with SQL database with MVC application. So we have written unit testing codes that apply the same business logic which connect with database.

For example we have written to insert, update, retrieve operation in unit testing which connect to database.

We have two different source one for Local or Staging application, and another Production application. So different database for Local and Production. Now our testing codes are connected with local database. Is this better way to use different database for unit testing codes to run?

Is changing connection string to change different database connection in web config file of Unit testing projection enough and right way to do or else do we have any other proper way to switch database based on different Solution configurations?

Help us the address this scenario.

Regards, Karthik.

Transactions doesn't work on some tests

I'm working with Laravel 5.2 and phpunit and i'm writing some test for my application. until now i got no problem, and today i encounter something weird and I can't find a way to handle it.

Some of my test file doesn't use transactions although the others does.

i use use DatabaseTransactions; in my TestCase class with is extended in every test file i got.

Most of my test works without any troubles but some of them does not.

Here is one which works withotut any troubles :

class V2LikeTest extends TestCase {

        protected $appToken;
        protected $headers;    

        public function setUp() {
            parent::setUp();
            $this->generateTopic(1);

        }

        /** LIKE TOPICS */
        /** @test */
        public function it_likes_a_topic() {
            $job = new ToggleLikeJob(Topic::first());
            $job->handle();

            $topic = Topic::first();
            $this->assertTrue($topic->present()->isLiked);
            $this->assertEquals(1, $topic->nb_likes);
        }
    }

and this one with troubles:

class V2TopicTest extends TestCase {

    private $appToken;
    private $headers;

    public function setUp() {
        parent::setUp();
        $this->generateCompany(1);

    }

    /** @test */
    public function it_create_a_topic() {
        $new_topic_request = new Request([
            'content' => str_random(100),
            'type' => Topic::TYPE_FEED_TEXT
        ]);
        $job = new CreateFeedTopicJob($new_topic_request->all());
        $job->handle();

        $this->assertCount(1, Topic::all());
    }

}

It's been a while now that i'm looking for the solution but not able to find it. Did someone already meet this troubles?

edit: GenerateTopic function use generateCompany just in case ;)

Can I fake calling methods in Ruby tests?

I'm running some tests on my Ruby code, but the method I'm testing calls a function in an external library responsible for sending push notifications. I want the calls it makes to be 'faked', so they don't actually get called. It'd also be helpful if they could return a standard response, or yield with a standard response. Is there any way to do this?

Run python tests in parallel

I tried to run my tests using pytest with xdist in order to speed up my tests (that are very slow since most of them involve database transactions with SQLAlchemy). I launched them with:

py.test -n 4

(since my macbook pro has 4 cores)

As result, tests run in half the time previously required, but many of them fail (they pass if I run them normally). So the problem seems to be that my code is not thread safe. My question is: how can I create tests that can be safely executed in parallel, considering that my code does not explicitly makes use of threads and async code execution? Is there a rule of thumb and/or special decorators/TestCases to use? And moreover... why speed becomes 2x instead of 4x that I was expecting?

ps. I'm using Python 3.5.1 and all my tests inherit from unittest.TestCase

Moq framework to test method execute times

Please look at my code below, the verification always failed. Anyone can help?

public class ViewModel
{
    private IMyDataService dataService = null;

    public ViewModel(IMyDataService dataService)
    {
        this.dataService = dataService;
    }

    public Dictionary<string, string> filters {get; set;}

    public void ProcessFilters()
    {
        dataService.ProcessFilters(filters);
    }
}

[TestMethod]
public void ProcessFilters_Test()
{
    var mockService = new Mock<IMyDataService>();
    ViewModel vm = new ViewModel(mockService.Object);
    Dictionary<string,string> filters = null;
    vm.ProcessFilters(filters);
    mockService.Verify(x=>x.ProcessFilters(filters), Times.Once);
}

Which Android Testing libraries should be used?

I am new to Android testing. I have used Espresso at one point for testing my app but it wasn't something that would reveal all the reasons I should use Espresso. So when I searched for Android testing, I got overwhelming number of libraries. Now I am trying to figure out what is the purpose of each of these libraries and when should I use which one?

Skimming through the internet, I found JUnit, Espresso, Mockito, RoboElectric, Monkey.

From what little I know,

  • JUnit is used for testing pure JAVA code because it tests the code in JVM.

  • Espress is used to test UI (however I used it to test the whole app i-e; logic and UI by running the tests on the emulator and verifying if the UI was visible after a certain logic, so I don't know why would one use JUnit)

Rest of them I don't know anything about. Can somebody tell the scenarios where each one of the mentioned libs will be used and why?

dimanche 29 mai 2016

Node Mock-fs - /path/to/file is not being mocked

Unit testing my gulp app in Mocha and using mock-fs from mock-fs repo .

In my app code I have:

console.log('sssssssssssssss ' + srcFile);
srcFile = fs.statSync(srcFile).mtime;

which shows sssssssssssssss /home/one/foo

In my test I have:

    mock({
        home: {
          one: { 
            foo: mock.file({
              content: 'nothing',
              mtime: new Date(Date.now())
            })
          },
        },
        bar: mock.file({
        content: 'nothing',
        mtime: new Date(1,1)
        })
    });

But I get the error Error: ENOENT, no such file or directory '/home/one/foo' when I run the test.

What I am doing wrong where /home/one/foo is not being mocked?

How to debug theories in xunit tests

I have big amount of similar tests which I implement as a theory using MemberData attribute. How can I navigate to each fallen test case and debug it?

Here an example:

    public const int A = 2;
    public const int B = 3;
    public const int C = 2;

    public static IEnumerable<object[]> GetTestCases
    {
        get
        {
            // 1st test case
            yield return new object[]
            {
                A, B, 4
            };

            // 2nd test case
            yield return new object[]
            {
                A, C, 4
            };
        }
    }

    [Theory]
    [MemberData("GetTestCases")]
    public void TestMethod1(int operand1, int operand2, int expected)
    {
        // Q: How can I debug only test case, which is failed?
        //...and break execution before exception will be raised
        var actual = operand1 + operand2;
        Assert.Equal(actual, expected);
    }

How to use mocks in Python?

I know that there are tutorials and other posts about mocks in Python but I'm new to testing and mocks, I read some posts and watched a tutorial but they confused me more. I have two examples that I just wrote fast and I wanna know how can I use mocks to test two examples.

In the first example test the the value that gets returned and in the second one test that a file gets created if we create a new instance of the 'MyFile' class.

1:

def get_link_tags(url):
    response = requests.get(url)

    pattern = re.compile("<link.*>")
    found_link_tags = pattern.findall(response.text)
    return found_link_tags

2:

class MyFile:
    def __init__(self, filename, content):
        self.content = content

        with open(filename, "w") as fl:
            fl.write(content)

Thank you

How to compare two CSV files in Mocha?

I am trying to write a unit test case for a file download feature in my NodeJS/ExpressJS app, that uses Mocha for testing.

I have no idea how to write the test though. The functionality is to check if a JSON to CSV parser module is working. I have a sample JSON file that I can feed into the module, and a CSV file that I can compare the result with, but I don't know how to compare the result with the fixture file.

TIA

Unit test a polymer web component that uses firebase

I have been trying to configure offline unit tests for polymer web components that use the latest release of Firebase distributed database. Some of my tests are passing, but others—that look nigh identical to passing ones—are not running properly.

I have set up a project on github that demonstrates my configuration, and I'll provide some more commentary below.

Sample: http://ift.tt/1qVjHu0

In that project, there are two suites of tests that work fine. The simplest is offline-test, which doesn't use web components at all. It simply shows that it's possible to use the firebase database's offline mode to run some unit tests. The heart of this trick is the in the suiteSetup method shown below—a trick I picked up from nfarina's work on firebase-server.

suiteSetup(function() {
  app = firebase.initializeApp({
      apiKey: 'fake',
      authDomain: 'fake',
      databaseURL: 'http://ift.tt/1X6dtGb',
      storageBucket: 'fake'
  });
  db = app.database();

  db.goOffline();
});

All the tests in offline-test pass.

The next suite is wct-firebase-demo-app_test.html, which test the eponymous web component. This suite contains a series of unit tests that are set up like offline-test and that pass. Following the idea of dependency injection, the wct-firebase-demo-app component has a database attribute into which is passed the firebase database reference, and this is used to make all the firebase calls. Here's an example from the suite:

  test('offline set string from web component attribute', function(done) {
    element.database = db;
    element.database.ref('foo').set('bar');
    element.database.ref('foo').once('value', function(snapshot) {
      assert.equal(snapshot.val(), 'bar');
      done();
    });
  });

I have some very simple methods in the component as well, in my attempt to triangulate toward the broken pieces I'll talk about in a moment. Suffice it to say that this test passes:

test('offline push string from web component function', function(done) {
    element.database = db;
    let resultRef = element.pushIt('foo', 'bar');
    element.database.ref('foo').once('value', function(snapshot) {
      assert.equal(snapshot.val()[resultRef.key], 'bar');
      done();
    });
  });

and is backed by this implementation in wct-firebase-demo-app:

  pushIt: function(at, value) {
    return this.database.ref(at).push(value);
  },

Once again, these all pass. Now we get to the real quandary. There's a suite of tests for another element, x-element, which has a method pushData:

  pushData: function(at, data) {
    this.database.ref(at).push(data);
  }

The test for this method is the only test in its suite:

  test('pushData has an effect', function(done) {
    element.database = db;
    element.pushData('foo', 'xyz');
    db.ref('foo').once('value', function(snapshot) {
      expect(snapshot.val()).not.to.be.empty;
      done();
    });
  });

This test does not pass. While this test is running, the console comes up with an error message:

    Your API key is invalid, please check you have copied it correctly.

By setting some breakpoints and walking through the execution, it seems to me that this error comes up after the call to once but before the callback is triggered. Note, again, this doesn't happen with the same test structure described above that's in wct-firebase-demo-app.

That's where I'm stuck. Why do offline-test and wct-firebase-demo-app_test suites work fine, but I get this API key error in x-element_test? The only other clue I have is that if I copy in a valid API key into my initializeApp configuration, then I get a test timeout instead.

How to test static java methods in groovy SPOCK framework?

I am trying to test static java method in SPOCK groovy framework using Maven.

Here is the java class public class DataController {

 private DataInterface userService;

    public void setUserService(DataInterface userService) {
        this.userService = userService;
    }
   public static int addNumber(){
        int a = 10;
        int b = 20;
        return a+b;
    }   

}

Here is the SPOCK test in groovy

@PrepareForTest([DataController.class])
class BasicMockStaticTest extends Specification {

@Rule PowerMockRule powerMockRule = new PowerMockRule();

    def "When mocking static"() {
        setup :
            PowerMockito.mockStatic(DataController.class)

        when :
            Mockito.when(DataController.addNumber()).thenReturn(30);

        then :
            DataController.addNumber() == 30
    }
 }

and the POM File snippet

   <dependencies>
    <!-- Spock Framework basic dependencies: -->
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.3.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <!-- The version have to be compatible with Groovy -->
        <version>1.0-groovy-2.3</version>
        <scope>test</scope>
    </dependency>
    <!-- To use Hamcrest matchers: -->
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <!-- To mock classes: -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.1</version>
        <scope>test</scope>
    </dependency>
    <!-- Use with cglib to mock classes without default constructor: -->
    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>2.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
  <groupId>org.codehaus.gmavenplus</groupId>
  <artifactId>gmavenplus-plugin</artifactId>
  <version>1.5</version>
 </dependency>
 <!-- Power mock dependencies -->
 <dependency>
 <groupId>org.powermock</groupId>
 <artifactId>powermock-module-junit4</artifactId>
 <version>1.5.4</version>
 <scope>test</scope>
 </dependency>

 <dependency>
 <groupId>org.powermock</groupId>
 <artifactId>powermock-module-junit4-rule</artifactId>
 <version>1.5.4</version>
 <scope>test</scope>
 </dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-classloading-xstream</artifactId>
<version>1.5.4</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
    <testSourceDirectory>E:\Workspace\Mars\rg\Spock\src\test\groovy</testSourceDirectory>
<pluginManagement>
    <plugins>
        <!-- GMavenPlus plugin -->
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.5</version>
            <executions>
                <execution>
                    <goals>
                     <goal>addSources</goal>
          <goal>addTestSources</goal>
          <goal>generateStubs</goal>
          <goal>compile</goal>
          <goal>testGenerateStubs</goal>
          <goal>testCompile</goal>
          <goal>removeStubs</goal>
          <goal>removeTestStubs</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
         <!-- Only required if names of spec classes don't match default    Surefire patterns (`*Test` etc.) -->
         <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.6</version>
    <configuration>
      <useFile>false</useFile>
      <includes>
        <include>**/*Test*.*</include>
        <include>**/*Spec*.*</include>

      </includes>

I have 4 test cases in the groovy folder , 3 are passing , but this static method test is giving error as

 When mocking static(BasicMockStaticTest)  Time elapsed: 0.104 sec  <<< ERROR!
   java.lang.IllegalStateException: Extension API internal error:   org.powermock.api.extension.proxyframework.ProxyFrameworkImpl could not be  located in classpath.
    at   org.powermock.modules.junit4.rule.PowerMockClassloaderExecutor.registerProxyframework(PowerMockClassloaderExecutor.java:60)
    at  org.powermock.modules.junit4.rule.PowerMockClassloaderExecutor.forClass(PowerMoc kClassloaderExecutor.java:50)
    at org.powermock.modules.junit4.rule.PowerMockRule.apply(PowerMockRule.java:31)
at org.spockframework.runtime.extension.builtin.MethodRuleInterceptor.intercept(MethodRuleInterceptor.java:37)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:87)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)

I am running mvn test to test these junits , I tried changing the version of cglib-nodep from 3.1 to 2.2.2 but it did not work.

I checked in the java build path following jar files are included

powermock-module-junit4-1.5.4
powermock-module-junit4-common-1.5.4
powermock-reflect-1.5.4
powermock-module-junit4-rule-1.5.4
powermock-classloading-base-1.5.4
powermock-classloading-xstream-1.5.4
powermock-api-support-1.5.4
powermock-core-1.5.4
groovy-all-2.3.1.jar
spock-core-1.0-grovy-2.3.jar

I also added powermock-mockito-release-full-1.5.4 but after adding that none of the test cases ran and build was success but that was not my intent.

I am suspecting may be some of the dependencies are missing or some of the existing are conflicting but not able to move forward.

Can any one tell what is wrong , I can move forward with the test case even if it fails , I will correct it but I need to remove the error first .

On a side note I did try groovyMock also but it gave nullpointer exception for static method , then I searched and found static method did not work with groovyMock.

I have tried top google link results with popular blogs and tutorial but none seems to work.