samedi 31 octobre 2015

Unit Testing for Django Projects

I've recently started for a new company and I've started on Django Project. Now I want to write unit tests to test the complete functionality of the Project. How do I proceed. One more thing I want to ask is how can I call the methods to the test files from the files for which test case has to be written. Let's say I have the following code in views :

class SourcesViewSet(viewsets.ViewSet): authentication_classes = (authentication.TokenAuthentication, authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) lookup_field = 'key'

def list(self, request):
    """
        Get a list of sources.
        ---
        request_serializer: SourceSerializer
        response_serializer: SourceSerializer
        responseMessages:
            - code : 200
              message : Success
            - code : 401
              message : Not authenticated
    """
    request_arrival_time = timezone.now()
    sources = Sensor.objects.filter(user=request.user,
                                    isTemplate=False)
    serializer = SourceSerializer(sources, many=True)
    response = Response(serializer.data, status=status.HTTP_200_OK)
    log_a_success(request.user.id, request, response.status_code,
                  request_arrival_time)
    return response

How test case can be written for this. Please suggest. Thanks.

Clojure - tests with components strategy

I am implementing an app using Stuart Sierra component. As he states in the README :

Having a coherent way to set up and tear down all the state associated with an application enables rapid development cycles without restarting the JVM. It can also make unit tests faster and more independent, since the cost of creating and starting a system is low enough that every test can create a new instance of the system.

What would be the preferred strategy here ? Something similar to JUnit oneTimeSetUp / oneTimeTearDown , or really between each test (similar to setUp / tearDown) ?

And if between each test, is there a simple way to start/stop a system for all tests (before and after) without repeating the code every time ?

Note : I am talking about unit-testing here.

Karma Jasmine test code inside

I',m learning AngularJS and how to unit test it. (If this is a stupid question, then I'm sorry)

I'm using Karma -> Jasmine and the test works fine if I test a .js file.

Karma.conf.js

// Karma configuration
// Generated on Sat Oct 31 2015 16:45:09 GMT-0600 (CST)

...
// list of files / patterns to load in the browser
files: [
  'angular.js',
  'angular.min.js',
  'angular-mocks.js',
  'controllerSpec.js',
  'Controller.js'  //WORKS
],
....

So if I move the javascript code from the Controller.js file to a <Script> block in Controller.cshtml file

...
// list of files / patterns to load in the browser
files: [
  'angular.js',
  'angular.min.js',
  'angular-mocks.js',
  'controllerSpec.js',
  'Controller.cshtml'  //DOESN'T WORK
],
....

When I run the test Karma throws:

Uncaught SyntaxError: Unexpected tokem ILLEGAL at //Controller.cshtml:1

Is it possible to test javascript code inside <script></script> in your html file?

How to inject springSecurityService Into Grails Domain Class for Controller Unit Testing in Grails 2.4.2

How do i inject springSecurityService in Grails Domain class While unit testing Controller,Below is the Sample Code, i keep getting error can not get encodePassword on null Object and similarly for getPrincipal();

 //Controller class
    class UserController{
     def save(){
         def user=new AppUser(params).save();
         render(user as JSON)  
      }
    }

    //Domain Class
    class User{
     transient springSecurityService
    String name
    String address
    String password
    String createdBy
    def beforeInsert(){
      password=springSecurityService.encodePassword(password);
      def principal = springSecurityService.getPrincipal() 
    }

//Controller Test
@TestMixin(GrailsUnitTestMixin)
@TestFor(UserController)
class UserControllerSpec {

   void setUp() {
   }
    void "test save"(){
     given:
     params.name="A"
     params.password="abc"
     params.address="XYZ" 
     when:
     controller.save();
     then:
     response.status=="200" 
    }

}

Write unit test for console application with arguments

currently i write a little program foobar.php, which is a console application. The program get a path to a file, read the content, do some magic and writes a result on "stdout".

Now i will write a test for this program and i'm not sure how to write such a test.

I found one solution (How to launch properly php cli script in phpunit test?).

Based on this url i can wirte a test with one method. In this method a call the program this proc_open(), catch the response from stdout and check it with $this->assertEquals() but I dont know if that's the right way.

Should strings in automated unit tests still be hard-coded when providing internationalization support?

When writing a (C++) program with internationalization support I'm aware that strings should usually be stored in an external translation database rather than hard-coded. However, I'm wondering if it's still common practice to hard-code strings used in unit test code.

My intuition is that hard-coding strings in unit tests is ok as the effort to translate test code would be wasted on the end user. However, maybe there are situations where it would be useful, such as localization testing / development?

I'm wondering what the common practice is. Thanks.

Jasmine test for angular directive: Actual is not a function

I have the following tests:

it("should load the directive without error", function () {
    expect($compile(inputElement)($scope)).not.toThrow();
});

and my input element contains my directive. My directive has a require on ngModel and the purpose of the test is for it to compile without error if the element the directive is on has the ngModel directive. All of this works in production, but for some reason my test is failing and I get the message:

Actual is not a Function in __pathToJasmine/jasmine.js (line 2207)

I'm also using Jasmine 2.0.

Now, I realize that the actual function is $compile, and once it's called with $scope it's not longer a function, but how would I test whether my directive compiled successfully or not?

Unit Testing ICommand Windows Phone 8.1

I have a question about unit testing using MvvmLight in Windows Phone 8.1.

I have the following ViewModel class:

 public class TestViewModel:MainViewModel
{

    public TestViewModel(Test.Services.INavigationService navigationService,IDialogService dialogService)
        : base(navigationService,dialogService)
    {
        this.TestCommand = new RelayCommand(NavigateToPage);
    }


    public ICommand TestCommand{get; private set;}

    private void NavigateToPage()
   {
     this.navigationService.NavigateTo(typeof(TestApp.TestPage));
   }

This code works fine. But how can I test the ICommand "TestCommand" ?

I tried to solve this problem this way in my UnitTestApp:

    [ClassInitialize]
    public static void Initialize(TestContext testContext)
    {

       testViewModel = SimpleIoc.Default.GetInstance<TestViewModel>();
    }

    [TestMethod]
    public void TestCommand_Test()
    {
        ICommand testCommand = testViewModel.TestCommand;

        bool canExecute = testCommand.CanExecute(null);

        Assert.IsTrue(canExecute);
    }

But went out to the following failure : "UnitTestApp.TestViewModel.Initialize has wrong signature. The method must be non static, public, does not return a value and should not take any parameter.... "

Perhaps the failure is not the method "TestCommand_Test" but the "Initialize" method. Can you help me, solving this problem ?

vendredi 30 octobre 2015

How to clear EF7 InMemory database between tests?

I'm experimenting with the InMemory database provider for EF7. It was easy enough to setup a context and start utilizing it. And it was great when I added my first test which made use of it.

public class NotificationsDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase();
    }

    public DbSet<Notification> Notifications { get; set; }
    public DbSet<NotificationTag> NotificationTags { get; set; }
}

and

public List<Notification> GetUnprocessedNotifications()
{
    var retval = new List<Notification>();

    using (var context = new NotificationsDbContext())
    {
        retval = context.Notifications.Where(n => n.ProcessState == NotificationState.Unprocessed).ToList();
    }
    return retval;
}

and a test

[TestMethod]
public void GetUnprocessedNotifications_Returns_CorrectNotifications()
{
    // setup
    var m = new NotificationManager(_notificationResource, _notificationEngine, _notificationValidation);
    m.CreateNotification(new Notification { Subject = "One", Message = "Test", ProjectId = Guid.NewGuid(), ProcessState = NotificationState.Processed, ProcessedOn = DateTimeOffset.Now });
    m.CreateNotification(new Notification { Subject = "Two", Message = "Test", ProjectId = Guid.NewGuid() });
    m.CreateNotification(new Notification { Subject = "Three", Message = "Test", ProjectId = Guid.NewGuid() });

    var r = m.GetUnprocessedNotifications();

    Assert.AreEqual(2, r.Count);
}

However, when I added my second unit test I started running into issues.

Because the database seems to hang around even when the object the context resides in has been disposed it makes it difficult to predict the results of specific queries when I'm performing my assertions.

Is there a way to wipe the InMemory database besides stopping the application?

Is there a more efficient way to use assert with arrays in C?

in one part of my program I need to use assert to test multiple arrays (5 sets total), and I was wondering if there's a more efficient way to do that besides what I am doing right now, which is basically just creating a new array every time. FYI I do have assert.h at the beginning of the program.

void UnitTest3D(void){
    double test1[3] = {0,0,0};
    double test2[3] = {5,0,0};
    assert(find3Ddistance(test1,test2) - 5) < 0.001);

    double test3[3] = {-2, -3, 3.4};
    double test4[3] = {-2, -3, -1.6};
    assert(find3Ddistance(test3,test4) - 5) < 0.001);

    double test5[3] = {-2, -3.2, -5};
    double test6[3] = {3, 1.8, 0};
    assert(find3Ddistance(test5,test6) - sqrt(75)) < 0.001);
    return;
    }

How To Get All Package's Code Coverage together In Golang?

I have a library consisting of several packages. When running tests, I am using '-cover' flag and its showing the coverage information for each package individually.Like follows:

--- PASS: TestSampleTestSuite (0.00s)
PASS
coverage: 28.7% of statements
ok      http://ift.tt/1LHekoF 13.021s
?       http://ift.tt/1Q0sc0g [no test files]

=== RUN   TestAbc
--- PASS: TestAbc (0.43s)
PASS
coverage: 27.7% of statements

Is there any way to get a full coverage overview easily to get good idea about coverage on the whole project?

Unit Testing Android SMS Receiver

i try to write an unit test on an BroadcastReceiver that gets informed when an SMS was received. Its not meant to be the default Application. Instead i just need this for an two factor authentication. For this case i created an PDU with [1].

But when i pass it down to the BroadcastReceiver the phone nr of the Sender never gets read by android it's just null. The body text is returned.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Test
public void testOnReceive() throws Exception {
    final byte[] decodedPDU = BaseEncoding.base16().decode(PDU);
    final ReceiveSmsBroadcastReceiver receiveSmsBroadcastReceiver = spy(new ReceiveSmsBroadcastReceiver(true));
    final Intent intent = new Intent();
    intent.putExtra("format",SmsConstants.FORMAT_3GPP);
    intent.putExtra("pdus", new Object[]{decodedPDU});
    intent.setAction("android.provider.Telephony.SMS_RECEIVED");
    intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, 1);
    receiveSmsBroadcastReceiver.onReceive(InstrumentationRegistry.getTargetContext(), intent);

In the receiver i do this to get the SMSMessage Objects:

@TargetApi(Build.VERSION_CODES.KITKAT)
private void getSMSKitKat(final Context context, final Intent intent) {
    final SmsMessage[] messagesFromIntent = Telephony.Sms.Intents.getMessagesFromIntent(intent);

I receive an SmsMessage array here, the body message is correct. But i need to test my check sender phone number before i can notify the UI that the SMS is received: But nr is always null here:

private boolean isCorrectSender(@Nullable final SmsMessage message) {
    if (message == null) {
        return false;
    }
    final String nr = message.getOriginatingAddress();

Can someone point me whats wrong here ?

PS: SMSConstants and PhoneConstants are all framework classes i took from AOSP to get it running because those APIs are non public

[1] http://ift.tt/1OeaNlu

How to load the same JSON file in both an Android app and local unit test?

I have an Android project that displays data from a JSON file. The file is read from the assets directory, following the approach below:

src/main/assets/my_file.json

InputStream is = getResources().getAssets().open(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// use StringBuilder to get file contents as String

I also have local unit tests which require the same JSON file. In order to avoid the slowness of Instrumentation tests, I am currently loading a duplicate of the file as below:

src/main/resources/my_copy.json

File testData = new File(getClass().getResource(filename).getPath());
InputStream is = new FileInputStream(testData);
// read File as before

Is there an approach that would allow the JSON file to be stored in one location, whilst running the unit tests on a local JVM?

How to avoid an onPause() with mockito?

I have this method

@Override
protected void onPause() {
    unsuscribeFromMessageDispatcher(RaffleListActivity.this);
    Intent service = new Intent(this, AsyncIntentService.class);
    service.putExtra("TASK", TASKID_GET_RAFFLE_LIST);
    stopService(service);
    super.onPause();
}

And when I make the test, if fails in the super.onPause(); How can I avoid this line with mockito?

Debugging a Stored Procedure from Test Script

I have a project - VS2015 #C - that uses Entiity Framework 6.

I also have a Test Project. My Test Script calls upon my Entity Framework which is mapped to a Stored Procedure I created using Studio Management Studio for SQL Server 2014.

Is it possible to step into my stored procedure from this Test Script Method?

I have installed SQL Server Database Tooling and I have set a break-point on the C# code that calls this Stored Procedure and I have checked 'Enabled SQL Server debugging in both the Test and Code Projects.

Everything is installed on my local server so no remote issues.

This is new to me :)

Is faking dependencies with interfaces or virtual methods a good design choice?

I am trying to learn unit testing but there is a design issue resulting from it. Consider class A has a dependency on class B. If you want to create a stub for B in order to unit test A, most isolation frameworks require that B has to be an interface or all the methods used by A must be virtual. B can't be a concrete class with non-virtual methods in essence in order to unit test.

This imposes major restrictions on the design of production code. If I have to create an interface for every dependency then number of classes will double. Also I create interfaces for volatile dependencies(likely to change in the future) or if the design requires it for extensibility. Polluting the production code with interfaces just for testing will increase its complexity significantly. Making all methods virtual doesn't seem to be a good solution also. It gives the inheritors impression that these methods are ok to be overridden even if they aren't and this is just a side effect of unit testing.

Does this mean that testable object oriented design doesn't allow concrete dependencies or does it mean that concrete dependencies shouldn't be faked? "Every dependency must be faked(stub or mock) to unit test correctly" is what I learned so far so I don't think latter is the case. Isolation frameworks other than JustMock and Isolator doesn't allow faking concrete dependencies without virtual methods and some argue that power of JustMock and Isolator lead to bad design. I think that the ability to mock any class is very powerful and it will keep the design of production code clean if you know what you are doing.

How to verify ThreadPool execute method which takes Lambda as parameter

I am currently testing a method in which I execute a runnable into a ThreadPool.

Here is the code for the method.

@Override
public void queueLogin(Connection connection, LoginPacket packet) {
    if(isRunning)
        loginPool.execute(() -> loginService.tryLogin(connection, packet));
}

Now I need to verify whether the execute method was invoked or not with the correct parameters.

Here is my test case

@Test
public void theQueueLoginShouldCallExecuteOnThreadPoolIfManagerIsRunning() {
    //Arrange
    loginManager.start();

    //Act
    loginManager.queueLogin(moqConnection, moqLoginPacket);

    //Assert
    verify(moqLoginPool).execute(() -> moqLoginService.tryLogin(moqConnection, moqLoginPacket));
}

But the test is failing saying

Argument(s) are different! Wanted:
executorService.execute(
    com.battletanks.game.server.unittests.manager.login.LoginManagerTests$$Lambda$2/1668016508@3d51f06e
);
-> at com.battletanks.game.server.unittests.manager.login.LoginManagerTests.theQueueLoginShouldCallExecuteOnThreadPoolIfManagerIsNotRunning(LoginManagerTests.java:84)
Actual invocation has different arguments:
executorService.execute(
    com.battletanks.game.server.manager.login.DefaultLoginManager$$Lambda$1/77269878@7ed7259e
);

I understand what is wrong here but I am not sure how to fix this.

How to delete a object that attached another object in C++?

I'm working on this unit testing. I feel like to delete the both drill and battery, but it seems doesn't work (battery cannot be deleted maybe). Can I do anything on the destructor so as to deal with this issue?

 void test_rover::testDisconnectBattery() {
        Drill* drill = new Drill();
        drill->connectBattery(new Battery(10));
        drill->disconnectBattery();

        //CPPUNIT_ASSERT(drill->Connected()==false);
        delete drill;
        CPPUNIT_ASSERT(Object::getCount()==0);
    }

Device.cpp (Device is the base of drill)

    Device::Device() {
    }

    Device::Device(const Device& copy) {
    }

    Device::~Device() {
       delete _battery;
    }

    void Device::connectBattery(Battery *b){ 
        _battery = b;
    }

    void Device::disconnectBattery(){
        _battery = NULL;
    }

Battery.cpp

Battery::Battery(int power) {
    _power = power;
}

Battery::Battery(const Battery& copy) {
}

Battery::~Battery() {
}

int Battery::Power(){
    return _power;
}

Unit testing with HttpContext.Application

I'm trying to unit test some code that reads a value from HttpContext.Current.Application but it keeps failing because it can't retrieve the value.

I've tried creating my own HttpContext, setting HttpContext.Current to it, then writing values to it but it does not seem to store the new values.

Code Referencing the HttpContext.Current.Application

public static void UpdateApplicationVariable(string keyToUpdate, object toSave)
{
    HttpContext.Current.Application.Lock();
    HttpContext.Current.Application[keyToUpdate] = toSave;
    HttpContext.Current.Application.UnLock();
}

public static object GetApplicationVariable(string keyToReturn)
{
    return HttpContext.Current.Application[keyToReturn];
}

Setup Code

HttpContext.Current = new HttpContext(
    new HttpRequest(null, "http://tempuri.org", null),
    new HttpResponse(null)
);

UpdateApplicationVariable("GeneralSettings", new GeneralSettings()
{
    NumberDecimalPlaces = 2
});

//settings is null
GeneralSettings settings = GetApplicationVariable("GeneralSettings") as GeneralSettings;

Android NPE running JUnit test

I'm trying to implement some tests in my application. One thing that I want to test is writing a java object to my db, then retrieving it and asserting the the object that comes out of the db matches the object that went in.

Here's my MySQLiteHelper application code:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.concurrent.atomic.AtomicInteger;

class MySQLiteHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "unittesttester.db";
    private static final int DATABASE_VERSION = 8;
    private static final String LOG_TAG = MySQLiteHelper.class.getSimpleName();

    private static final int WEATHER_STALENESS_PERIOD_MS = 60 * 5 * 1000; //5 minutes

    private AtomicInteger mOpenCounter = new AtomicInteger();
    private static MySQLiteHelper mInstance = null;
    private SQLiteDatabase db;
    private Context mContext;

    public static MySQLiteHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySQLiteHelper(context.getApplicationContext());
        }

        return mInstance;
    }

    private MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(WeatherTable.CREATE_TABLE_WEATHER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion <= DATABASE_VERSION) {
            onCreate(db);
        }
    }

    private synchronized SQLiteDatabase openDatabase() {
        final int i = mOpenCounter.incrementAndGet();
        if (i == 1) {
            db = getWritableDatabase();
        }
        return db;
    }

    private synchronized void closeDatabase() {
        final int i = mOpenCounter.decrementAndGet();
        if (i == 0) {
            db.close();
        }
    }

    private void truncateWeatherTable() {
        db = openDatabase();
        db.delete(WeatherTable.TABLE_WEATHER, null, null);
        closeDatabase();
    }


    public void deleteAndInsertWeather(Weather weather) {
        db = openDatabase();
        db.beginTransaction();
        try {
            truncateWeatherTable();
            insertWeather(weather);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            closeDatabase();
        }
    }

    private void insertWeather(Weather weather) {
        db = openDatabase();
        db.insert(WeatherTable.TABLE_WEATHER, null, makeWeatherCv(weather));
        closeDatabase();
    }

    public Weather getWeather() {
        db = openDatabase();
        String sql = "SELECT * FROM " + WeatherTable.TABLE_WEATHER;
        Cursor c = null;
        Weather weather = null;
        try {
            c = db.rawQuery(sql, null);
            if (c.moveToFirst()) {
                weather = makeWeather(c);
                //If sample too old return null
                if (System.currentTimeMillis() - weather.getTimestamp() > WEATHER_STALENESS_PERIOD_MS) {
                    weather = null;
                    truncateWeatherTable();
                }
            }
        } finally {
            if (c != null) {
                c.close();
            }
            closeDatabase();
        }
        return weather;
    }


    private Weather makeWeather(Cursor c) {
        Weather weather = new Weather();
        weather.setTimestamp(c.getLong(c.getColumnIndex(WeatherTable.COLUMN_TIMESTAMP)));
        weather.setElevation(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_ELEVATION)));
        weather.setTemperature(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_TEMPERATURE)));
        weather.setDusk(c.getInt(c.getColumnIndex(WeatherTable.COLUMN_DUSK)));
        weather.setNighttime(c.getInt(c.getColumnIndex(WeatherTable.COLUMN_NIGHTTIME)));
        weather.setGravity(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_GRAVITY)));
        weather.setDaytime(c.getInt(c.getColumnIndex(WeatherTable.COLUMN_DAYTIME)));
        weather.setHumidity(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_HUMIDITY)));
        weather.setPressure(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_PRESSURE)));
        weather.setOkta(c.getDouble(c.getColumnIndex(WeatherTable.COLUMN_OKTA)));
        weather.setDawn(c.getInt(c.getColumnIndex(WeatherTable.COLUMN_DAWN)));
        return weather;
    }

    private ContentValues makeWeatherCv(Weather weather) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherTable.COLUMN_TIMESTAMP, weather.getTimestamp());
        contentValues.put(WeatherTable.COLUMN_TEMPERATURE, weather.getElevation());
        contentValues.put(WeatherTable.COLUMN_TEMPERATURE, weather.getTemperature());
        contentValues.put(WeatherTable.COLUMN_DUSK, weather.getDusk());
        contentValues.put(WeatherTable.COLUMN_NIGHTTIME, weather.getNighttime());
        contentValues.put(WeatherTable.COLUMN_GRAVITY, weather.getGravity());
        contentValues.put(WeatherTable.COLUMN_DAYTIME, weather.getDaytime());
        contentValues.put(WeatherTable.COLUMN_HUMIDITY, weather.getHumidity());
        contentValues.put(WeatherTable.COLUMN_PRESSURE, weather.getPressure());
        contentValues.put(WeatherTable.COLUMN_OKTA, weather.getOkta());
        contentValues.put(WeatherTable.COLUMN_DAWN, weather.getDawn());
        return contentValues;
    }
}

Here's my test class for the class above:

import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;

import org.junit.Test;
import static org.mockito.Mockito.*;

public class MySQLiteHelperTest extends AndroidTestCase {

    private MySQLiteHelper db;
    private Weather mockedWeather = mock(Weather.class);

    @Override
    public void setUp() throws Exception {
        super.setUp();
        RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_");
        db = MySQLiteHelper.getInstance(context);

        when(mockedWeather.getDawn()).thenReturn(0);
        when(mockedWeather.getDaytime()).thenReturn(1);
        when(mockedWeather.getDusk()).thenReturn(2);
        when(mockedWeather.getElevation()).thenReturn(3.0);
        when(mockedWeather.getGravity()).thenReturn(4.0);
        when(mockedWeather.getHumidity()).thenReturn(5.0);
        when(mockedWeather.getNighttime()).thenReturn(6);
        when(mockedWeather.getOkta()).thenReturn(7.0);
        when(mockedWeather.getPressure()).thenReturn(8.0);
        when(mockedWeather.getTemperature()).thenReturn(9.0);
        when(mockedWeather.getTimestamp()).thenReturn(10L);
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    public void testGetInstance() throws Exception {

    }

    public void testOnCreate() throws Exception {

    }

    public void testOnUpgrade() throws Exception {

    }

    @Test
    public void testDeleteAndInsertWeather() throws Exception {
        db.deleteAndInsertWeather(mockedWeather);
        Weather actualWeather = db.getWeather();
        assertEquals(mockedWeather.getDawn(), actualWeather.getDawn());
        assertEquals(mockedWeather.getDaytime(), actualWeather.getDaytime());
        assertEquals(mockedWeather.getDusk(), actualWeather.getDusk());
        assertEquals(mockedWeather.getElevation(), actualWeather.getElevation());
        assertEquals(mockedWeather.getGravity(), actualWeather.getGravity());
        assertEquals(mockedWeather.getHumidity(), actualWeather.getHumidity());
        assertEquals(mockedWeather.getNighttime(), actualWeather.getNighttime());
        assertEquals(mockedWeather.getOkta(), actualWeather.getOkta());
        assertEquals(mockedWeather.getPressure(), actualWeather.getPressure());
        assertEquals(mockedWeather.getTemperature(), actualWeather.getTemperature());
        assertEquals(mockedWeather.getTimestamp(), actualWeather.getTimestamp());

    }

    public void testDeleteWeather() throws Exception {

    }

    public void testInsertWeather() throws Exception {

    }

    public void testGetWeather() throws Exception {

    }

    public void testWeatherMakeCv() throws Exception {

    }
}

When I run the test I am getting a NPE during my test. It seems to occur when the MySQLiteHelper class has its db = getWritableDatabase() line. getWriteableDatabase() is a public method from the base class.

I don't think I understand why this test results in an NPE. In my test I call the static method, MySQLiteHelper.getInstance(Context context) which should initialize the class. It is my assumption that calling getInstance will provide me with a fully initialized instance of MySQLiteHelper. Why does this not seem to be happening?

How to do unit test on the generated directive with different value in attr?

I have angular directive "Directive" with isolated scope and it's template and Unit test.

I insert 3 directive on the html page with different scope values.

I want to check out that each directives has own value which I have entered in the attributes and that there are 3 elements with Unit test.

class Directive {
 constructor () {
 'ngInject';

 let directive = {
 restrict: 'E',
 templateUrl: 'Directive.html',
 controller: Controller,
 controllerAs: 'vm',
 bindToController: true,
 scope: {
 buttonName: '@',
 classes: '@css'
 }
 };

 return directive;
 }
}
<label class="{{vm.classes}}" ng-model="radioModel" uib-btn-radio="{{vm.buttonName}}">{{vm.buttonName}}</label>

<div class="btn-group">
 <directive button-name="First" css="btn btn-primary classButton"></directive >
 <directive  button-name="Second" css="btn btn-primary classButton"></directive >
 <directive  button-name="Third" css="btn btn-primary classButton"></directive >
 </div>

unit testing Android studio JnI

I am a newbie of some sorts, so please bear with me for my kind of question. I have an android studio project with a JNI part where I wrote a C programm. I want to ask how I can go about testing the C programm, which testing frame work will be most suitable, plus these C programme does not have a main() method. Several frameworks I found do not have clear documentation especially for a newbie. I will be glad you just point me in the right direction. Thanks

Jenkins/SonarQube unit testing code coverage for JavaScript

We set up Jenkins/SonarQube to fail a build if a developer commits new code that has less than 70% of unit testing code coverage for Java. We would love to do the same for JavaScript. This turned out to be problematic.

To get SonarQube to analyze JavaScript unit tests you have to use an option like this (taken from Jenkins context):

sonar.javascript.jstestdriver.reportsPath=${WORKSPACE}/my-project/generated-reports/jstd

The problem is that using JSTestDriver (http://ift.tt/13lC3CG) is out of the question because it's old and not compatible with modern JavaScript frameworks like AngularJS or ReactJS.

Question: has anybody encountered and solved this problem?

"Content type not set" when Unit Testing Spring RESTful controller

I have a Rest controller similar to this one:

@RestController
public class UserRestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/activate", method = RequestMethod.POST)
    public ResponseEntity<UserDTO> activate(
            @RequestParam(required = true) final String email,
            @RequestParam(required = true) final String key) {

        UserDTO userDTO = userService.activateAccount(email, key);
        return new ResponseEntity<UserDTO>(userDTO, HttpStatus.OK);
    }
}

When I invoke it using Postman and I don't send the 'key' parameter, I receive this JSON message:

{
    "timestamp": 1446211575193,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required String parameter 'key' is not present",
    "path": "/user/activate"
}

On the other hand, I am testing this method with JUnit and the MockMVC Spring utility.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class UserRestControllerTest {

    private static MockMvc mockMvc;

    @Mock
    private UserService userService;

    @InjectMocks
    private UserRestController userRestController;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(userRestController)
                .setMessageConverters(
                        new MappingJackson2HttpMessageConverter(),
                        new Jaxb2RootElementHttpMessageConverter()).build();

    }

    @Test
    public void testActivateRequiredParams() throws Exception {

        mockMvc.perform(
                MockMvcRequestBuilders.post("/user/activate")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isBadRequest())
                .andExpect(
                        MockMvcResultMatchers.content().contentType(
                                UtilsUnitTest.APPLICATION_JSON_UTF8))
                .andExpect(
                        jsonPath(
                                "message",
                                is("Required String parameter 'email' is not present")));

     }
}

But when I execute this test I notice that the response is not a JSON message. In fact, I get an exception:

java.lang.AssertionError: Content type not set

Particularly, the completed result is

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /user/activate
          Parameters = {}
             Headers = {Content-Type=[application/x-www-form-urlencoded]}

             Handler:
                Type = com.company.controller.UserRestController
              Method = public org.springframework.http.ResponseEntity<com.company.dto.UserDTO> com.company.controller.UserRestController.activate(java.lang.String,java.lang.String)

               Async:
       Async started = false
        Async result = null

  Resolved Exception:
                Type = org.springframework.web.bind.MissingServletRequestParameterException

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

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = Required String parameter 'email' is not present
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

I deduce that when an exception is thrown this is not converted to JSON format (I get a correct JSON result when I send the email and key parameters)

The question is obvious: what should I change in the Unit Test configuration to get a JSON error message in case of an exception be thrown?

Detailed information on tests with nosetest --with-html-out

I am playing a bit with nosetest and I am missing the feature where I can output detailed information about the tests.

For example I am testing a colored spectrum random generator where the asserts are put on particular frequencies. However, It would be interesting to output an html report with a frequency plot and some statistics about the test.

At the end of the day I would like to be able to insert in the report some detailed information in such manner:

def test():
   """ Example. """
   report.insertPlot() #numpy plot
   report.insertText("Some text")
   report.insertSeparator() # would probably insert a <hr> tag

I currently notice that just doing this below does not work.

def test():
   """ Example. """
   print "Some text that I wish to see in my report"

How to generate a detailed test report with nose?

How to unit-test a razor-view

When Scott Guthrie first blogged on Razor, he wrote

The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

However, I can find no other statement (or example) regarding razor-testability. There are pointers to using the CodelanguageServie or RazorGenerator or some self-made renderer - non of which I would call "by design".

Is it currently possible to unit test a razor view the simple way? (In an asp.net mvc-application, that is. I.e. NancyFx brings testability in it's nancy.testing-package.)

(And currently I don't care if views should be tested or not.)

I know there are loads of questions like this one, but most of them are rather old...

How can 'The Humble Dialog Box' be implement in Python 3 using the unittest framework?

This link shows an example using the nose test suite, however I am interested in understanding how this would look with the standard unittest test suite.

Further, in the link provided, what is the purpose of the @properties that are used, i.e. @selectionList.Setter

The output of test class

Can someone please explain what the output would be from this?

I've just come across the following in a test class and don't really understand it, would someone be able to shed some light please?

public class Test1 extends TestCase{

   private Collection collection;

@Before
Public void setUp() {
    collection = new ArrayList();
    System.out.println(”setUp");
}

@After
Public void tearDown() {
    collection.clear();
    System.out.println("tearDown");
}

@Test
Public void testEmptyCollection() {
    assertTrue(collection.isEmpty());
    System.out.println(“Empty");
}

}

MVP Tutorial for Beginner

What are some good resources for learning more about this design pattern, including how to implement effective unit tests for it?

These resources should offer sample code snippets, preferably in Python though not necessarily. Further, aside from the code snippets the resources should also offer some detailed explanations regarding what MVP is, why it is used, why it is effective, and when not to use it.

Finally, the resources should not assume a professional or university level of training. It's ok if they assume you have a firm understanding of basic, and even 'above basic' programming principles.

Jasmine unit testing $timeout (expect($timeout).toHaveBeenCalledWith(n);)

I would like to unit test an Angular.js $timeout to check that it has been called with the correct duration/delay value.

The assertion would look something like this:

expect($timeout).toHaveBeenCalledWith(n);

My Angular code looks roughly like the following:

$timeout(function() {
    // do something
}, attrs.timeout || 30000);

I want to ensure that without an override (attrs.timeout) it is called with 30000 and with the override it is called with that override.

I have tried a decorator like this:

// from: http://ift.tt/1PZ07GB
beforeEach(module(function($provide) {
    $provide.decorator('$timeout', function($delegate) {
        return jasmine.createSpy($delegate);
    });
}));

Plus several other methods but I cannot seem to get it to work.

I am using Angular 1.3.20, Jasmine 2.3.4

Any suggestions gratefully received.

AngularJS unit testing service method return promise

I have service which make call to server, in that service i have one method which perform CRUD operations. I want to test my service. I stuck at testing all CRUD criteria i.e add, update ,delete etc.

my method in service:-

getPromiseForCRUDOperation(masterRecord : masterDefinitionEntity.MasterRecord, request : masterDefinitionEntity.MasterRequest) {
  return this.$http.post(config.Configs.getServerUrl() + "/masterRecord/" + request.type, masterRecord);
}

here request.type is enum for CRUD operations.(0-ADD,1-UPDATE and so on)

How to verify the derived type of a parameter passed to a mocked function

I have a base class and two derived classes, like this:

class Base { ... };
class DerivedA : public Base { ... };
class DerivedB : public Base { ... };

I also have an interface class which I'm mocking (with Google Mock), like this:

class MockSomeInterface : public SomeInterface
{
  public:
    MOCK_METHOD1(someMethod, void(Base* basePtr));
};

I can expect calls to the mocked method like this, not verifying the parameter in the call at all:

EXPECT_CALL(mockSomeInterfaceObj, someMethod(_))
  Times(2);

What i would like to do is verify the type of the parameter given to someMethod, to check that it is in fact called with a DerivedA* once and a DerivedB* once, instead of just twice with any parameter.

Managing dependencies on c# Unit Test

I'm starting to make some tests with Unit Tests (not TDD, just writing some tests at this moment) using Visual Studio and a strange questions came in my mind after a error explore into my Test Project.

First of all, I created a Web Api 2 project, created my Model, Controllers and other stuff. I've separated my repository, configured dependency injection and the project was fully functional.

After that, I created my Unit Test project, add a reference to the previous Web Api project, created a mock for my repository, instantiate my controller, passed the mock as constructor injection, called the method and asserted the result. The code was functional but when I compile, it complains about the can't find the ApiController from System.Web.Http.

The tries were:

  • The first thing I've tried was, searching for the dependency in "Add Reference" context menu. I added but the version was different, so was not working.

  • The second thing worked, but was very ugly. Again entered in "Add Reference" context menu, browsed the directory from Web Api project and choosen the bin folder and selected all dlls. That worked, but was terrible, because once I version that test, will be broken because was referencing a path probably not available on the checkout computer.

  • The third try was copy the package.json from the Web Api project and paste on the Unit Test project and run on the NuGet console "Update-Packages -Reinstall". The third option worked, but I don't know if is the correct way to do that.

TL;DR;

How do you guys reference all DLLs dependencies on Unit Test project?

Django PyMongo Unit testing

I have a django application with mongodb backend. Pymongo is used for database operations. Django ORM is not used in the project. How I can write Unit test cases for the project?

How Unit Test a PHP Command Class

I'm trying to unit test a PHP Application. I'm also new to Unit Testing and maybe this shouldn't be one of my first Unit Test Cases, but still I need to get this done, so...

I have a PHP command Class with 2 methods and a __construct(). the execute method loops through an array (obtained by a DBAL read) and calls executeSingleRow, which reads the DB, makes some consideration and, just if a few conditions are satisfied, calls the execute method of another command.

I just can't figure out how a good Unit Test can be done here, or how should I modify the code.

Here are my Class methods:

public function __construct(
    $registry,
    $firstTableRepository,
    $secondTableRepository,
    AnotherCommand $anotherCommand,
    JobLogRepository $logger = null
)
{
    $this->registry = $registry;
    $this->stagione = $this->registry->get('stagione');
    $this->firstTableRepository = $firstTableRepository;
    $this->secondTableRepository = $secondTableRepository;
    $this->anotherCommand= $anotherCommand;
    $this->logger = $logger;
    $this->error = false;
}

public function execute($toReplace, $replacer, $selected)
{
    foreach ($selected as $selectedRow) {
        firstTableID = $selectedRow['ID'];
        $this->executeSingleRow($toReplace, $replacer, firstTableID);
    }
    if ($this->error) {
        $this->keyException(null, 'Procedura terminata con errori');
    }
}


public function executeSingleRow($toReplace, $replacer, firstTableID)
{
    if ($toReplace == $replacer) {
        $this->error = true;
    } else {
        $firstTableRow = $this->firstTableRepository->readByID(firstTableID);
        if (!empty($firstTableRow)) {
            $CODE = $firstTableRow['CODE'];
            $newCODE = str_replace($toReplace, $replacer, $CODE);
            if ($newCODE != $CODE) {
                $articoloNuovo = $this->secondTableRepository->readByCode($newCODE);
                if ($articoloNuovo) {
                    $secondTableIDNuovo = $articoloNuovo['secondTableID'];
                    try {
                        $this->anotherCommand->setJobLog($this->jobLog);
                        $this->anotherCommand->execute($secondTableIDNuovo, 'G', firstTableID);
                        return;
                    } catch (\Exception $e) {
                        $this->error = true;
                    }
                } else {
                    $this->error = true;
                }
            } else {
                $this->error = true;
            }
        } else {
            $this->error = true;
        }
    }
}

Thanks a lot for being so kind to read and answer if possible!

Mockito creates different instances?

I have an enterprise Java bean with some injected dependencies. I also have a test class which mocks these dependencies with @Mock and @Produces annotations. Everything works fine except that Mockito seems to create different instances for the bean (MyClass@50778) and for the test class (MyClass@50835), therefore verify() calls always fail since all the calls happen on the bean instance and the check is done on the test instance. The most interesting part is that on the continuous integration server the tests run fine, the problem seems to be with my local environment. I see no significant difference between the CI server logs and the output of the local run.

I'm aware that I can't include all of my local preferences, project settings, logs, whatsoever here, so it's hopeless that somebody could blindly point out what the actual problem is here. What I'm looking for is a general guideline... a hint that I could follow to hunt down the problem: what can possibly make Mockito to create different instances for my injected dependency?

Running Meteor Integration and Unit Test

I have a MeteorJS project and doing some test. I had written unit test which runs fine then later added some server integration test for my controllers. Now I have only my Integration test working and nothing comes up on my Unit Test report anymore. Even when my test files are moved from the tests/server/integration folder to test/server/unit folder, the application just runs with no report on the html-report or terminal. Any hints? Thanks.

//in tests/server/integration/store.controller.js
describe('StoreController', function(){
var storeController; //assign an instance of IronRouter to variable
//other code block and actual test comes here
});

//in tests/server/unit/store.collection.js
describe('StoreCollection', function(){
var Stores = null;
beforeEach(function(){
    MeteorStubs.install();
    //use mock for collection class
    Stores = new Meteor.Collection('stores'); 
    spyOn(Stores, 'find');
    spyOn(Stores, 'aggregate');
});

afterEach(function(){
    MeteorStubs.uninstall();
});

describe('StoreCollection.findActiveStores', function(){
    it('should list all stores that are active', function(){
         expect(StoreCollection.findActiveStores()).toBeDefined();
         //test spy has been called or called with given parameters
         expect(Stores.find).toHaveBeenCalled(); 
    });
});
});

jeudi 29 octobre 2015

Why should i choose NUnit over MSTest as a Unit Testing Framework

Why should i choose NUnit over MSTest as a Unit Testing Framework?
Please provide tutorial site link as well.

JUnit Test Method for a method that returns a string

Below is my Cylinder class, and then the JUnit test that I am trying to use to test the getLabel method I wrote. I am having trouble understanding how to properly form a test method when I am testing for a string that the user will input.

public class Cylinder {
   private String label = "";
   private double radius;
   private double height;
   private static int count = 0;

   /**
   * Creates a new Cylinder object with a given label, radius, and height.
   * 
   * @param label2 The name of the cylinder returned as a String.
   * @param radius2 The radius of the cylinder as a double.
   * @param height2 The height of the cylinder as a double.
   */
   public Cylinder(String label2, double radius2, double height2, int count2) {
      setLabel(label2);
      setRadius(radius2);
      setHeight(height2);
      setCount(count2);
   }
   /**
   * This method is respondible for getting the label from the user 
   * and returns a string representation of the label.
   *
   * @return String representation of the label of the Cylinder.
   */
   public String getLabel() {
      return label;
   }

Below is my JUnit test class, which I am using to create a test for each method in my Cylinder class.

public class CylinderTest {

   private String label = "";
   private double radius;
   private double height;

   /*
   *
   */
   @Test public void labelTest() {
      Cylinder c1 = new Cylinder("", radius, height);

      String result = c1.getLabel(label);

      Assert.assertEquals(" ", label);

How do I get started making unit tests for my Android app?

This seems like a silly question but I have an app in Android Studio and I'd like to try some TDD/Unit testing. I tried adding a tests folder and adding a class manually in the explorer but found I can only add Java classes under my main src folder. How can I simply add a tests folder at the same level as my src folder and create Java classes for it? Do I need something in my build.gradle?

Android Studio Test Folder not appearing for Unit Test Artifact

The androidTest appeared on my Android Studio when the Test Artifact was switched to Android Instrumentation Test. However, when the Test Artifact was switched back to Unit Test. The entire androidTest folder disappear. This project was a migration from Eclipse. I have multiple flavor for my project.

Gradle.build

sourceSets {
    main {
       // manifest, java, renderscript, aidl, assets, res detail etc etc
    }
    flavour1 {
       // manifest, java, renderscript, aidl, assets, res detail etc etc
    }
    flavour2 {
       // manifest, java, renderscript, aidl, assets, res detail etc etc
    }
    flavour3 {
       // manifest, java, renderscript, aidl, assets, res detail etc etc
    }
    flavour4 {
       // manifest, java, renderscript, aidl, assets, res detail etc etc
    }
    androidTest.setRoot('tdd/test')
    androidTest {
         java.srcDirs = ['tdd/test/java']
    }
}

I don't understand why it disappear for Unit Test but appear for Android Instrumentation Test.

In .NET what is a way to test an Async Lock, proving that reentrancy is prevented?

I have a method like this:

public async Task ConnectAsync()
{
    using (await _connectMutex.LockAsync())
    {
        ...
    }
}

...which prevents reentrancy. What is a simple way to unit test this method, to prove that reentrancy is prohibited?

Jasmine testing get request after promise. Error: No pending request to flush?

I need your help. I'm getting an error: Error: No pending request to flush !

Here is my factory:

angular.module('myapp')
.factory('WebDB', function ($http, LocalDB) {
    function lastChangeParameter(resource) {
        return new Promise(function (resolve, reject) {
            LocalDB.getLastChange(resource).then(function (time) {
                resolve("last_change=" + time);
            });
        }); 
    }
    return {
        getBuildings: function () {
            return lastChangeParameter("buildings").then(function (lastChange) {
                return get(sourceDB + "buildings" + "?" + lastChange);
        });
    }};
});

And test:

describe('Testing webdb module...', function () {
var WebDB;
var httpBackend;
var mockedLocalDB;
var $rootScope;

beforeEach(function () {
    module("myapp");

    mockedLocalDB = {
        getLastChange: function (resource) {
            return new Promise(function (resolve, reject) {
                resolve(0);
            });
        }
    };
    module(function ($provide) {
        $provide.value('LocalDB', mockedLocalDB);
    });

    inject(function ($injector) {
        WebDB = $injector.get("WebDB");
        httpBackend = $injector.get("$httpBackend");
        $rootScope = $injector.get("$rootScope");
    });
});



afterEach(function () {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

describe("WebDB", function () {
    describe("getBuildings", function () {
        it("should download updated buildings", function () {
            var respondData = {};
            httpBackend.expectGET('http://ift.tt/20evRft').respond(200, respondData);


            WebDB.getBuildings().then(function (buildings) {
                result = buildings;
            });
            $rootScope.$digest();
            httpBackend.flush();
            expect(result).toEqual(respondData);
        });
    });

I think this happens because before get request I'm calling some db function, which is promise. Without that call it works perfectly, but I really need to ask local DB for the lastChange value before get request. What's wrong with my test or factory? Thanks for your help!

Creating a read stream over a string

I have a function that takes an input stream, processes its data, and then returns something, basically a more complicated version of this:

fn read_number_from_stream(input: &mut io::BufRead) -> io::Result<u32> {
  // code that does something useful here
  Ok(0)
}

Now I want to write a test for this function.

#[test]
fn input_with_zero_returns_zero() {
  let test_input = read_from_string("0\n");
  assert_eq!(Ok(0), read_number_from_stream(test_input));
}

How do I implement read_from_string? Older versions of Rust apparently provided std::io::mem::MemReader, but the entire std::io::mem module seems to be gone in more recent versions of Rust (I'm using the unstable 1.5 branch).

How to Unit-Test Thread which takes time to perform action

I have Thread which runs while the program runs and polls a queue and check whether it has object and if yes then it calls method on the object

Here is the code :

while(isRunning){
        synchronized (loginQueue) {
            if(loginQueue.peek() != null) {
                Object[] loginObjectWithConnection = loginQueue.poll();
                tryLogin(loginObjectWithConnection);
            }
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}

Here is the tryLogin method

private void tryLogin(Object[] loginObjectWithConnection) {
        LoginPacket packet = (LoginPacket)loginObjectWithConnection[0];
        Connection connection = (Connection)loginObjectWithConnection[1];

        try {
            if(playerDataService.arevalidCredentials(packet.getUserName(), packet.getPassword())) {

                if(!playerDataService.isPlayerBanned(packet.getUserName())){ //Player exists in the system

                    communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.PLAYER_BANNED));

                } else{ //Player is not banned

                }
            } else { // Player does not exist
                communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.INVALID_USER));
            }
        } catch (SQLException e) {
            communicationService.sendTCP(connection, packetFactory.makeLoginFailurePacket(StringConstants.SERVER_ERROR));
            e.printStackTrace();
        }
}

Now my problem is that I want to test the invocations of these service methods but when I run the unit tests they won't work as it takes time to reach the point of tryLogin and till then JUnit fails. I tries using Thread.sleep() but I know it is not the right way to do it as it fails sometimes and pass sometimes.

Here is what I have in my Unit Test

@Test
public void theExpectedMessageShouldBeSentIfUserIsBanned() throws InterruptedException, SQLException {
    //Arrange
    when(moqLoginQueue.peek()).thenReturn(object);
    when(moqLoginQueue.poll()).thenReturn(object);
    LoginFailurePacket packet = new LoginFailurePacket(StringConstants.PLAYER_BANNED);
    when(moqPacketFactory.makeLoginFailurePacket(StringConstants.PLAYER_BANNED)).thenReturn(packet);
    when(moqPlayerDataService.arevalidCredentials(anyString(), anyString())).thenReturn(true);
    when(moqPlayerDataService.isPlayerBanned(anyString())).thenReturn(true);

    //Act
    loginManager.start();
    Thread.sleep(10); //Dirty hack -.-

    //Assert
    verify(moqCommunicationService).sendTCP(any(Connection.class), eq(packet));
}

Access scope variable in unit test

I'm trying to access the scope.loading variable in my unit test. The idea is to test that the $on listener fires correctly.

scope.loading is defaulted to false in the link function of my directive. It should be updated to true when the $on function receives the 'loadingPosts' $broadcast from $rootScope.

However, the test case always fails saying the scope.loading is undefined. Where am I going wrong?

Here's my test case:

'use strict';

describe('ngPress', function()
{
    beforeEach(module('ngPress'));

    describe('ngpLoader directive', function()
    {
        it('loading event fires', function()
        {
            inject(function($compile, $rootScope)
            {
                var scope = $rootScope.$new();

                var element = $compile('<ngp-loader type=\"posts\"></ngp-loader>')(scope);

                $rootScope.$broadcast( 'loadingPosts' );

                expect( scope.loading ).toEqual( true );
            });
        });
    });
});

And here's the directive:

(function ()
{
    angular.module('ngPress').directive('ngpLoader',
        [function ()
        {
            var link = function(scope, element, attrs)
            {
                scope.loading = false;

                scope.$on( 'loading'+scope.type.capitalizeFirstLetter(), function()
                {
                    scope.loading = true;
                });

                scope.$on( scope.type+'Loaded', function()
                {
                    scope.loading = false;
                });

                scope.$on( scope.type+'LoadFailed', function()
                {
                    scope.loading = false;
                });
            };

            return {
                link: link,
                restrict: 'E',
                replace: true,
                template: '<div class="loader" ng-show="loading"></div>',
                scope: {
                    type: '@'
                }
            };
        }]);
}());

NodeJS unit test : sinonJS stub not working for method that had a spy

I'm stuck on a subset of functions that I'm trying to create stubs for. I've got 50+ tests that are passing, many of them with stubs. I'm following the same pattern for this subset of functions but for some reason they are behaving differently. The only difference between these functions and the successful stubs are a) the successful stubs are stubbed and restored in the beforeEach and afterEach functions whereas the broken stubs are being stubbed in the test where they run and b) the broken stubs previously had sinon spies attached to them, but I restore them before stubbing them so not sure if that's an issue.

Here's the code I'm testing. It's really simple:

    function gatherMeritEmployeesSeries(callback) {
    console.log(jobName + " : gatherMeritEmployees");
    gatherMeritEmployees(function (err) {
        if (err) {
            callback(err);
        } else {
            callback();
        }
    })
}

Here's the test I'm trying to run:

    describe('when gatherMeritEmployeesSeries function is called', function () {
    it('should call the callback', function () {
        t.gatherMeritEmployees.restore(); //removes the spy
        var gather = sinon.stub(t, 'gatherMeritEmployees');
        gather.callsArgWith(0, 'error');
        gatherMeritEmployeesSeries(cbspy);
        assert(cbspy.called);
        assert(cbspy.calledWith('error'));
        gather.restore();
    });
});

I'm using lcov-report to see my code coverage and it's showing this:

lcov report shows I'm not getting into the callback

When I run my tests, my report says this:

52 passing (176ms) 1 failing

1) transformEmployee.js when gatherMeritEmployeesSeries function is called should call the callback:

  AssertionError: false == true
  + expected - actual

  -false
  +true

So even though I should be passing in 'error' and calling the callback with 'error', my test is failing. Thanks in advance if you can help.

How To Determine Which Unit Test Covered a Function or Method

From a Python perspective, how can one determine the unit test(s) which covered a function or method, or generally any line of code that was hit by a test in the suite by the test runner? It seems reasonable that this information should be at hand given the coverage tools know the specific code that was hit, but I cannot find any way to get at this information (I am using py.test as my test runner with the coverage and pytest-cov modules).

One approach I have found is to just put a pdb.set_trace call into the code, but it would be really helpful if I could find a more elegant way that didn't require modifying the code under test.

UWP Unit Tests fail to initialize client proxy in Visual Studio 2015

Using Visual Studio 2015 Community edition, I am unable to run even the most basic Universal Windows Unit Tests. Once I create a test, and try to run it through Test Explorer, the code compiles and seems to deploy the unit test windows app. The app stays up for about 10 seconds, then closes itself. The test runner's result for the test: Inconclusive: Failed to initialize client proxy: could not connect to test process . Running Visual Studio as an Administrator didn't seem to have any effect.

To create the sample project that caused my error:

  1. Start a new Project
  2. From the templates, choose: Templates > Visual C# > Windows > Universal > Unit Test App (Universal Windows)
  3. Write a simple test: Assert.IsTrue( true )
  4. In the menu, Test > Run > Run all tests

The Output window for the Tests option shows this:

Checking whether required frameworks are installed...

Registering the application to run from layout...

Deployment complete (3566ms). Full package name: "edd458e2-c3b1-4d8a-b7c3-5669e2fe7d75_1.0.0.0_x86__97afpx01qh2gg"

Error : DEP3000 : Attempts to stop the application failed. This may cause the deployment to fail. Exception from HRESULT: 0x92330047

Updating the layout...

Deployment complete (104ms). Full package name: "edd458e2-c3b1-4d8a-b7c3-5669e2fe7d75_1.0.0.0_x86__97afpx01qh2gg"

Modifying the output of XMLTestrunner

I would like to modify the testcase name that outputs when running my tests using the XMLTestrunner. The reason I need to do this is that I have some scenarios where when a particular test is being executed, I want it to report that another test name has passed because the functionality is the same. So all I want to change is the test name, nothing else. I've written a decorator to change the test name(function name) but when the test result is displayed, it still displays the old test name in the test report. See samples of python code below; I also tried assigning func.name = testcase in the decorator but that didn't help. The function name is actually changed but I'm not sure how to make xmlrunner take this instead.

decorator

def testcase(testname):
    def decorator(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        wrapper.__name__ = testname
        wrapper.__dict__ = func.__dict__
        wrapper.__doc__ = func.__doc__
        return wrapper
    return decorator

Test case

class MyTestClass(unittest.Testcase):
    def setUp():
        ...
    def tearDown():
        ...

    @testcase('new_test_name')
    def_test_old_test_name(self):
        #do the same thing

if __name__ == "__main__":
    unittest.main(testRunner=xmlRunner.XMLTestRunner(out='reports'))

Automated tests for the user interface of a jQuery application

I usually use Jasmine to unit test AngularJS applications.

I'm working on a jQuery-intensive web application that shows and hides elements based on clicks and other events.

I would like to test something of the sort - when I click this button, I expect this element to show.

My question is - what sort of tools do I have available for this purpose? Thank You.

Team Foundation Build 2013 and Octopus Deploy - How to reject a package when build or unit test fail?

We are using Team Build 2013 to create builds, and Octopus to deploy. The problem is that I can't figure out how to prevent my builds to reach the build server on failure, and finally prevent them from appearing on Octopus when the build or unit test fail. I have change the "Retention Policy" to erase builds when it fails, but Octopus still sees the empty builds. My ultimate goal is to rollback the checkin if the build or unit test fails. But again, I can't find an event called "On Build failure" or something similar. I tried to use the Post-Build Script, but it is not called when a build fails.

jasmine unit testing for knockout application

I am not able to trigger jasmine tests using karma-jasmine. getting below error while running karma task..

29 10 2015 10:40:51.922:DEBUG [web-server]: serving (cached): C:/apps/161_new_resp_UnittestPOC/ca_module/caUI/src/target/spec/tests/jasmine-spec.js 29 10 2015 10:41:31.897:WARN [PhantomJS 1.9.8 (Windows 7 0.0.0)]: Disconnected (1 times), because no message in 40000 ms.

MY test file is simple and its below..

describe("simple Tests", function () {
    it("should make an Ajax request to the correct URL", function () {
      expect(5).toEqual(5);
    });
  });

below is my karma-config-file

files: [
        'src/target/spec/tests/jasmine-spec.js'
        ]

Unit testing directive's controller

I am struggling to get the controller from within a directive for unit testing. Here is my angular app:

angular.module('test-app', [])

    .controller('loadingCtr', ['$scope', function ($scope) {

    }])

    .directive('loading', function() {
        return {
            restrict: 'E',
            controller: 'loadingCtr'
       };
    });

Here is my unit test code:

describe('loading', function () {

    beforeEach(inject(function($rootScope, $compile) {

        var fooElement = $compile('<loading></loading>')($rootScope);
        var fooController = fooElement.controller('loading');

        $rootScope.$digest();
        console.log(fooController);
    })); 

    describe('loading: testing loading directive', function() {
        it('should create loading directive', function() {
        });
    });
});

Here is a plnkr to mess around with: http://ift.tt/1NbjWKb

fooController always returns as undefined. I've tried using the following examples I've found online, but I always get the same results:

Unit testing a directive that defines a controller in AngularJS

http://ift.tt/1NbjWKd

Is there something obvious here that I am missing?

Eclipse CDT/C++ - Unit Tests with timeout?

I want to perform a Unit Test for a C++ project in Eclipse CDT and the test should have a timeout, if it takes longer than 60ms. For Java developement we have Junit Tests where we can set up a timeout in the annotation. So i´m asking if there is a similar kind of test framework for C++ in Eclipse CDT. At the moment, i have just found CUTE and CppUnit Testing, but they seem to have no timeout for there tests.

Thanks for your help!

WordPress Unit Testing with is_plugin_active()

The plugin I'm unit testing with phpunit has a dependency on another plugin, using is_plugin_active().

When testing the dependency in my unit test that function always returns false/inactive, when the it is definitely active, because it's working properly in the plugin itself. It seems to be accessible, so there must be some logic error when it comes to this wordpress core function.

This is my code:

function test_requirementsMet_true() {
$this->assertTrue(is_plugin_active('pluginFolder/plugin.php'));
}

Does anyone know of a work-around?

VectorCast test function pointer

I am having problems testing a scenario in VectorCast. Dont know what it expects ?

here is the thing.

I am testing a function - say FuncA which calls int FuncB ( ENUM, &FuncC )

I want to Stub FuncB and pass Enum and check if FuncC address is passed.

While stubbing, user code for the second parameter I gave was like this

<> = ( FuncC );

I tried putting it in Input and Expected section both

It takes lot of time t execute and then fails with the Harness Error

Can you please give a solution to this?

Thanks!!

Test a private method with PrivateObject

I have a class,

public class VoiceElementsLine : ILine
{
    private SipChannel _incomingSipChannel;


    private void AnswerSipChannel()
    {
        _incomingSipChannel.Answer();
    }

What I want to test is to test the private method AnswerSipChannel be executed. I want to use PrivateObject.

How?

My code:

   [Fact]
    public void AnswerSipChannel_Should_Execute()
    {
        var privateObject = new PrivateObject(typeof (VoiceElementsLine));
        var mockSipChannel = new Mock<SipChannel>();

    }

How to skip code for testing or convert oracle syntax to h2

My team and I are working with oracle database for development and production. But to save time, we decided to use H2 database for testing because it is fast.

Now we run into a problem related to SQL grammar.

public void lock(Collection<String> locks) {
    if (locks== null || locks.size() == 0)
        return;

    Connection dbc = null;
    Statement st = null;
    String q = null;
    try {
        dbc = db.getConnection();
        dbc.setAutoCommit(false);
        st = dbc.createStatement();
        st.setFetchSize(fetchSize);
        q = "LOCK TABLE resource_lock IN EXCLUSIVE MODE";
        st.executeUpdate(q);

        // Update the lock info in DB
        List idLists = DbUtil.splitIdList(locks);
        Iterator i = idLists.iterator();
        while (i.hasNext()) {
            List idList = (List) i.next();
            q =
                "DELETE FROM resource_lock\n" +
                "WHERE " + DbUtil.generateStrIn("lock", idList);
            st.executeUpdate(q);
        }

        st.close();
        st = null;
        dbc.commit();
        dbc.close();
        dbc = null;
    } catch (SQLException e) {
        throw new DbException(e, q);
    } finally {
        DbUtil.cleanup(log, null, st, dbc);
    }
}

The issue was occurred at "LOCK TABLE resource_lock IN EXCLUSIVE MODE" which this is oracle only grammar. In the test I wrote it always throws syntax error which states

Caused by: com.resource.db.DbException: Database Error: Syntax error in SQL statement "LOCK[*] TABLE RESOURCE_LOCK IN EXCLUSIVE MODE "; SQL statement:
LOCK TABLE resource_lock IN EXCLUSIVE MODE [42000-160]
Last SQL was:
LOCK TABLE resource_lock IN EXCLUSIVE MODE

I was wondering if there are syntax for H2 that has equivalent operation. If there isn't any then I was wondering how would I skip this section for testing since many of other classes method uses this to update the database. I would not want the other test to fail because of this.

Unit Testing Ember Services that Fetch Data

I have an ember service thats primary concern is to fetch data for a specific model and the descendants of the model. The reason I am using this in a service is because the route for this particular type is using a slug which is not the primary key and therefore needs to do a store.query instead of store.find. When we fetch this model I have some logic that peeks the ember store to see if we can load it from there before going to the api query. Also this vendor is watching for the slug change and updating the current model based on that.

The problem I am having is that this seems to have very little documentation when it comes to how to test a thing like this. In fact I don't see a section on testing services anywhere in the guides here http://ift.tt/20d8nr7

This is a snippet of the service in question.

import Ember from 'ember';

export default Ember.Service.extend({
    _vendorSlug: null,
    vendor: null,

    vendorSlug: function (key, value) {
        if (arguments.length > 1) {
            if (this._vendorSlug) {
                return this._vendorSlug;
            }

            this._vendorSlug = value;
        }

        return this._vendorSlug;
    }.property(),

    ensureVendorLoaded: function (slug) {
        var service = this,
            vendorSlug = slug || service.get('vendorSlug'),
            currentVendor = service.get('vendor'),
            storedVendor;

        if (!Ember.isNone(currentVendor) && (vendorSlug === currentVendor.get('slug'))) {
            return new Ember.RSVP.Promise((resolve) => {
                        resolve(currentVendor);
                    });
        } else {
            var storedVendors = service.store.peekAll('vendor').filter((vendor) => { 
                return vendor.get('slug') === vendorSlug;
            });

            if (storedVendors.length) {
                storedVendor = storedVendors[0];
            }
        }

        if (!Ember.isNone(storedVendor)) {
            service.set('vendorSlug', storedVendor.get('slug'));

            return new Ember.RSVP.Promise((resolve) => {
                    resolve(storedVendor);
                });
        }

        return service.store.queryRecord('vendor', {slug: vendorSlug}).then((vendor) => {
            service.set('vendor', vendor);
            service.set('vendorSlug', vendor.get('slug'));

            return vendor;
        });
    },

    _vendorSlugChanged: function () {
        if (this.get("vendorSlug") === this.get("vendor.slug")) {
            return;
        }

        this.ensureVendorLoaded();
    }.observes('vendorSlug')
});

How do I mock an object of a class with parameterized constructor?

For the code

public class A{
    public A (B b, C c){
    //do something here
    }
}

For testing, I wanted to create a mock object. What I am doing now is

B bmock = mock(B);
C cmock = mock(C);
A aobject = new A(bmock, cmock);

However, this doesn't allow me call verify() on aobject as it is not mocked. How to do that?

Testing if a promise is called from a controller unit-testing AngularJS

I am writing unit tests in AngularJS using karma and I would like to test the following controller whether is calling or not the service. I cant use spyOn because it is a promise and not a function. I don't want to test the service itself but I can't figure out how can I do it.

    $scope.deleteItem= function(itemId){
    service.deleteItem(itemId)
    .then(function(){
      $scope.info("Deleted");
      $scope.getData();
    }, function(data){
      $scope.critical('error');
    });
};

DateTime Interface to be used for unit testing

Hi So I have created an interface for datetime like this:

public interface ITimeProvider<T>
{
    T Now { get; }
    string ToShortDateString();
}

And then I have one implamentation of that interface like this:

public class DateTimeProvider : ITimeProvider<DateTime>
{

    private DateTime _date;

    public DateTime Now
    {
        get { return DateTime.Now; }
    }

    public  DateTimeProvider()
    {

        _date = new DateTime();
    }
    public string ToShortDateString()
    {
        return _date.ToShortDateString();
    }
}

Then I am using it in my main unit and want to use property injection but i ran into some problems, here is a snap of what I have:

public class Atm : IAtm
{
   public ITimeProvider _timeProvider { get;set; }
}

This doesn't work as I don't specifiy a type. I could just do

public ITimeProvider<DateTime> _timeProvider { get;set; }

But then I wouldn't be able to use another timeprovider. I have also considered(and is the only solution I could come up with) is to make ATM generic so something like this

 public class Atm<T> : IAtm
 {
      public ITimeProvider<T> _timeProvider { get;set; }
 }

But then I feel like I can't use property injection, is there any other way I can do this so I will be able to test it?

not able to select month dropdown value for gmail registration form

How to select value from birthday month dropdown in gmail registration form using webdriver

driver.findElement(By.xpath("//label[@id='month-label']/span/div/div")).click(); driver.findElement(By.xpath("//label[@id='month-label']/span/div[2]/div[@id=':5']")).click();

Using docker for unit test

I run a MySQL container with --net=host option.

So now i can make unit test using:g:

self.db = MySQLdb.connect(host="127.0.0.1", user="XYZ", passwd="XYZ", db="TEST_DB")

The problem is when I try to dockerize my unit test, linking the container with my MySQL container, the 127.0.0.1 IP is not valid. I need to use the real ip for the MySql container, or use the DNS (/etc/hosts file).

So I need to alter the ip 127.0.0.1 for the name of the MySQL host.

I imagine that there is a better way to do this? I can, for example, alter the /etc/hosts file of my development enviroment.

How can I access an inner Enum in Grails Test?

I have a Groovy domain like this:

package fantasy

    class Notification {

        enum NotificationType {
            INVITE_GENERAL, INVITE_CONTEST
        }

        NotificationType type

        String emailTo
        User toUser
        User fromUser
        String message
        boolean wasReadByToUser
        boolean wasReadByFromUser
        boolean fromUserRemoved

        Date dateCreated

        static constraints = {
            type(blank: false)
            toUser(nullable: true)
            emailTo(email: true, blank: false)
        }

        static mapping = {
            autoTimestamp true
        }
    }

And I need to access a notification type in a Grails.Groovy/Spock test...

How can I get at the Enum, as I've tried just about everything I can do. Here is my test so far:

package fantasy

import grails.test.mixin.TestFor
import spock.lang.Specification

/**
 * See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
 */
@TestFor(Notification)
@Mock([Notification, User])
class NotificationSpec extends Specification {


    // Notification
    Notification notification 
    // *** Here is my issue *** //
    Notification.NotificationType type = Notification.NotificationType.INVITE_CONTEST

    // Fields
    String emailTo = "fmulder@fox.com"
    String message = "Trust No One"
    boolean wasReadByUser = false
    boolean wasReadByFromUser = false
    boolean fromUserRemoved = false

    // Date
    Date dateCreated

    // Mocks
    def toUser
    def fromUser

    def setup() {
        toUser = Mock(User)
        fromUser = Mock(User)
        dateCreated = new Date()

    }

    def cleanup() {
        toUser = null
        fromUser = null
        dateCreated = null
    }

    void "test valid entry will validate"() {
        setup:
        notification = new Notification(
            type: type,
            emailTo: "danaScully@fox.com",
            toUser: toUser,
            fromUser: fromUser,
            message: message,
            wasReadByUser: false,
            wasReadByFromUser: false,
            fromUserRemoved: false,
            dateCreated: dateCreated
        ).save(failOnError: false, flush: true)
        expect:
        Notification.count() == 1
        notification.validate()
    }

}

How can I access that inner Enum?

Resttemplate unit testing

i am trying to unit test a method which is calling a resttemplate inside. But somehow my test is not working. The method that i want to test looks so

public Integer createAccount(Request request) {
    final String uri = "http://localhost:8080/stubs/otl/account/create";
    return restTemplate.postForObject(uri, request, Integer.class);
}

My Unit tests looks so

@InjectMocks
AccountServiceImpl accountService;

@Mock
RestTemplate restTemplate;

@Value("${url.otl}")
private String urlOtl = "http://localhost:8080/stubs/otl/";

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void createAccountTest(){

    MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);

    mockServer.expect(requestTo(urlOtl+"account/create"))
            .andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("1", MediaType.APPLICATION_JSON));

    Request request = new Request();
    Integer result = accountService.createAccount(request);
    mockServer.verify();
    Assert.assertEquals("1", String.valueOf(result));
}

When i ran the test i get as response java.lang.AssertionError: Further request(s) expected 0 out of 1 were executed at org.springframework.test.web.client.MockRestServiceServer.verify(MockRestServiceServer.java:167)

Can somebody tell me what i am missing or doing wrong.

Angular 2 unit tests with Karma

I learn Angular 2 and now try to do some unit tests using Karma. I configured my project base on this article http://ift.tt/1O9xpDB but when I'm running unit tests I got below error:

WARN [web-server]: 404: /base/src/angular2/angular2 Error: XHR error (404 Not Found) loading http://localhost:9876/base/src/angular2/angular2

I have gulp tasks which compiles my ts files into javascript.

karma.conf.js

module.exports = function (config) {
config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: http://ift.tt/1ft83uu
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    // list of files / patterns to load in the browser
    files: [
        'node_modules/traceur/bin/traceur-runtime.js',
        { pattern: 'src/build/**/*.js', included: false, serve: true },
        'node_modules/es6-module-loader/dist/es6-module-loader.js',
        'node_modules/systemjs/dist/system.js',
        'node_modules/angular2/bundles/angular2.dev.js',
        'test-main.js',
        {
            pattern: 'src/test/**/*spec.js',
            included: false,
            serve: true,
            watch: true
        }
    ],


    // list of files to exclude
    exclude: [
        'src/build/app.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: http://ift.tt/1gyw6MG
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: http://ift.tt/1ft83KQ
    reporters: ['progress', 'html'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: http://ift.tt/1ft83KU
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    plugins: [
        'karma-jasmine',
        'karma-chrome-launcher',
        'karma-jasmine-html-reporter'
    ]
})
};

test-main.js

/* global System */
/* global __karma__ */

// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () { };

// Set the base url of our scripts
System.baseURL = '/base/src/';
// Here we set all the preffixes so that we'll
// be able for example to import 'test/test_name'
// instead of 'scripts/build/test_name'
System.paths = {
    'test/*': '/base/src/test/*.js',
    'build/*': '/base/src/build/*.js',
    'angular2/*': 'angular2/*',
    'rx': 'rx'
};

// paths that include spec and ends with .js
function onlySpecFiles(path) {
    return /spec\.js$/.test(path);
}

// takes paths and normalize them to module names
// by removing a base url preffix and .js suffix
function karmaFileToModule(fileName) {
    return fileName.replace(System.baseURL, '')
        .replace('.js', '');
}

Promise.all(
    Object.keys(window.__karma__.files) // Takes all files that served by karma
        .filter(onlySpecFiles)  // choose only test files
        .map(karmaFileToModule) // normalize them to module names
        .map(function (moduleName) {
            return System.import(moduleName) // import each module
                .then(function (module) {
                    if (module.hasOwnProperty('main')) {
                        module.main(); //expose the tests
                    } else {
                        throw new Error('Module ' + moduleName + ' does not implement main() method.');
                    }
                });
        })).then(function () {
        __karma__.start(); // after all tests were exposed
    }, function (error) {
        console.error(error.stack || error);
        __karma__.start();
    });

header-spec.ts

    /// <reference path="../../typings/jasmine/jasmine.d.ts" />

import {Header} from 'build/components/header/header';

export function main() {
    describe('header component', () => {

        it('should add string to header names', () => {
            var header = new Header();
            var name = 'foo';
            header.addName(name);
            expect(1).toBe(1);
        });
    });
}

header.ts

    import {Component, View, NgFor} from 'angular2/angular2';



@Component({
    selector: 'header'
})
@View({
    templateUrl: 'build/components/header/header.html',
    directives: [NgFor]
})
export class Header {
    names: Array<string>;

    constructor() {
        this.names = new Array<string>();
    }

    addName(name: string) {
        this.names.push(name);
    }
}

When I remove import Header component in my test file, tests are going ok, so it's problem with import { Component...} from 'angular2/angular2'. I don't know why karma is trying to load this as/base/src/angular2/angular2` file. I appreciate your help.

Nunit Testing with Moq

I recently started learning Unit Test in MVC and used NUnit Framework for Test Cases. My problem is, i cannot understand for what should i write Test case. Imagine i have CRUD operation and i want to Test them, so what should be my Test case condition.

Here is my Interface class:

public interface IUserRepository 
{ 
    //Creating Single User Records into database using EF.
    bool CreateUser(tbl_Users objUser);

    //Updating Single User Records into database using EF.
    void UpdateUser(tbl_Users objUser);

    //Deleting Single User Records from database using EF.
    bool DeleteUser(long IdUser);
}

Here is my Repository Class:

public class UserRepository : IUserRepository
{
    DBContext objDBContext = new DBContext();      

    /// <summary>
    /// Creating new User Record into Database
    /// </summary> 
    /// <param name="objUser"></param>
    public bool CreateUser(tbl_Users objUser)
    {
        bool blnResult = false;
        objUser.MiddleName = string.IsNullOrEmpty(objUser.MiddleName) ? string.Empty : objUser.MiddleName.Trim();
        objUser.Photo = string.Empty;
        objUser.Approved = false;
        objUser.CreatedDate = DateTime.Now;
        objUser.DeleteFlag = false;
        objUser.UpdBy = 0;
        objUser.UpdDate = DateTime.Now;
        objDBContext.tbl_Users.Add(objUser);
        blnResult = Convert.ToBoolean(objDBContext.SaveChanges());
        return blnResult;
    }

    /// <summary>
    /// Updating existing User Record into Database
    /// </summary> 
    /// <param name="objUser"></param>
    public void UpdateUser(tbl_Users objUser)
    {
        objUser.MiddleName = string.IsNullOrEmpty(objUser.MiddleName) ? string.Empty : objUser.MiddleName.Trim();
        objUser.Approved = true;
        objUser.UpdBy = objUser.IdUser;
        objUser.UpdDate = DateTime.Now;
        objDBContext.Entry(objUser).State = EntityState.Modified;
        objDBContext.SaveChanges();
    }

    /// <summary>
    /// Deleting existing User Record from Database
    /// </summary> 
    /// <param name="IdUser"></param>
    public bool DeleteUser(long IdUser)
    {
        bool blnResult = false;
        tbl_Users objUser = objDBContext.tbl_Users.Where(x => x.IdUser == IdUser).Single();
        objUser.ConfirmPassword = objUser.Password;
        objUser.UpdDate = DateTime.Now;
        objUser.DeleteFlag = true;
        blnResult = Convert.ToBoolean(objDBContext.SaveChanges());
        return blnResult;
    }        
}

And Here is My Controller class

public class UserController : Controller
{
    tbl_Users objUser = new tbl_Users();
    UserRepository Repository = new UserRepository();        

    [ValidateAntiForgeryToken]
    [HttpPost]
    public ActionResult Create(tbl_Users objUser)
    {
        if (ModelState.IsValid)
        {
            try
            {
                Repository.CreateUser(objUser);
                return RedirectToAction("Update", "User");
            }
            catch
            {
                return View();
            }
        }
        return View();
    }       

    [ValidateAntiForgeryToken]
    [HttpPost]
    public ActionResult Update(tbl_Users objUser)
    {
        Repository.UpdateUser(objUser);
        return View();
    }

    public ActionResult Delete(long IdUser = 0)
    {
        bool blnResult = Repository.DeleteUser(IdUser);
        if (blnResult)
        {
            return View("Delete");
        }
        else
        {
            return View();
        }
    }
}

Here are Test cases which i tried to Execute using Moq

[TestFixture]
public class UserControllerTest
{
    UserController Controller;

    [SetUp]
    public void Initialise()
    {
        Controller = new UserController();
    }       

    [Test]
    public void DeleteTest()
    {
        var ObjUser = new Mock<IUserRepository>();

        ObjUser.Setup(X => X.DeleteUser(It.IsAny<long>())).Returns(true);

        var Result = ObjUser.Object.DeleteUser(1);
        Assert.That(Result, Is.True);
    }        

    [Test]
    public void CreateTest()
    {
        tbl_Users User = new tbl_Users();
        Mock<IUserRepository> MockIUserRepository = new Mock<IUserRepository>();
        MockIUserRepository.Setup(X => X.CreateUser(It.IsAny<tbl_Users>())).Returns(true);

        var Result = MockIUserRepository.Object.CreateUser(User);

        Assert.That(Result, Is.True);
    }         

    [TearDown]
    public void DeInitialise()
    {
        Controller = null;
    }
}

Can anyone tell me, how to Write test cases for above Controller Action Method with brief description about test cases using Moq.

Java JUnit Refactoring Tests to remove identical tests

I am new to JUnit. Currently have two separate JUnit test classes which both have 4 tests in, except one of the tests is identical for both test classes. Is there an easy way of somehow refactoring the code so that I can in a way 'import' the common test into both classes?

I have considered making a superclass to extract the common tests, however in this case it seems a bit overkill.

Any suggestions?

Many thanks.

How to deal with Setter/Getter-Methods from Mocks?

So I am still having trouble with the usage of Mockito. So let's assume I have following class (Please ignore the logic, or structure of it, it's just a short example I created from another class, with different names and so on.) :

public class Restaurant(
    @Autowired
    private CustomerService customerService;

    private CustomerInputData updateCustomer(CustomerInputData inputData){
        final String customerId = inputData.getID();
        final Customer customer = customerService.getCustomerById(customerID);
        if(customer.getAddress() != null){
            inputData.setCustomerName(customer.getCustomerName());
            inputData.setCustomerCity(customer.getCustomerCity);
            inputData.setCustomerLanguage(customer.getLanguage);
        }

        return inputData
    }
}

So my understanding of Unit-Tests is, to isolate all dependencies. Here I would have the Customer-class and the Customer-Service.

So to write a test-class, I would currently do following:

public class RestaurantTest()
{
    @Mock(name="customerService");

    private CustomerService customerService;

    @InjectMocks
    private Restaurant classUnderTest;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void updateCustomer_WithValidInput_ShouldReturnUpdatedInput(){
        //Some Mocking first
        final String customerId = "customerId";
        final Customer customer = mock(Customer.class);
        final final CustomerInputData = mock(CustomerInputData.class);

        doReturn(customer).when(customerService.getCustomerById(any(String.class)));
        doReturn(customerId).when(inputData.getId());

        doReturn("address").when(customer.getAddress());
        doReturn("Name").when(customer.getName());
        doReturn("City").when(customer.getCity());
        doReturn("Language").when(customer.getLanguage());

        doNothing().when(inputData).setCustomerName(any(String.class));
        doNothing().when(inputData).setCustomerCity(any(String.class));
        doNothing().when(inputData).setCustomerLanguage(any(String.class));

        verify(customer.getAddress(), atLeastOnce());
        verify(customer.getName(), atLeastOnce());
        //and so on...

        verify(inputData, atLeastOnce()).setCustomerName(eq("Name"));
        verify(inputData, atLeastOnce()).setCustomerCity(eq("City"));
        verify(inputData, atLeastOnce()).setCustomerLanguage(eq("Language");

    }
}

So currently I have no Assert, I only check if the right methods get called. The reason, why I try to do this like this, and not let the Test-class call the setter/getter is because of isolation. Let's assume inputData.setCustomerCity is broken, my test would fail. So it is depending on the CustomerInputData-Class.

Now how do I approach these getter and setters, what is the best practice?

Do I have not understood Mockito good enough? When I use mock(), can I then just use the setter-methods and gethods, and don't need to worry about using doReturns and so on?

I know it is a whitebox-test, I know the methods and what's going on.

Spring Boot REST Controller Test with RequestMapping of Properties Value

Regarding Unit Testing of Spring Boot REST Controller, I got a problem with @RequestMapping and application properties.

@RestController
@RequestMapping( "${base.url}" )
public class RESTController {
    @RequestMapping( value = "/path/to/{param}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
    public String getStuff( @PathVariable String param ) {
        // implementation of stuff
    }
}

I am working with several profiles for the application and therefore I have several application-{profile}.properties files. In each file the base.url property value is set and present. I also have a different Spring Context Configuration for testing, which only differs in just one Bean from the productive version.

My Unit Test looks like the following, with using JUNit and Mockito / RestAssured:

@ActiveProfiles( "dev" )
@RunWith( SpringJUnit4ClassRunner.class )
@SpringApplicationConfiguration( classes = SpringContextConfigTest.class )
public class RESTControllerTest {

private static final String SINGLE_INDIVIDUAL_URL = "/query/api/1/individuals/";

@InjectMocks
private RESTController restController;

@Mock  
private Server mockedServer; // needed for the REST Controller to forward

@Before
public void setup() {
  RestAssuredMockMvc.mockMvc( MockMvcBuilders.standaloneSetup(restController).build() );
 MockitoAnnotations.initMocks( this );
}

@Test
public void testGetStuff() throws Exception {
  // test the REST Method "getStuff()"
}

Problem is, that the REST Controller is working when started in the production mode. In the unit test mode, the ${base.url} value is not set and an exception is thrown, when building the mockMvc object:

java.lang.IllegalArgumentException: Could not resolve placeholder 'base.url' in string value "${base.url}"

I also tried it with the following approaches, but with different exceptions:

  • @IntegrationTest on Test,
  • @WebAppConfiguration,
  • using the webApplicationContext to build the MockMVC
  • autowiring the RESTController in the Test
  • defining the REST Controller Bean in the SpringContextConfigTest Class manually

and various other combinations, but nothing seems to work. So how do I have to go on, in order to make it work? I think it's a Context configuration issue with the two different config classes, but I don't know how to solve it or how to do it "right".