FAQ Database Discussion Community


How would you test this route code?

javascript,node.js,unit-testing,express,sequelize.js
I have the following route code. User is a sequelize model, jwt is for creating a JWT token. I want to avoid hitting the db, so I want to stub out both dependencies. User.create returns a Promise. I want to be able to assert that res.json is actually being called....

Writing the most basic Unit test in Angular 2?

javascript,unit-testing,karma-runner,ecmascript-6,angular2
Problem: As soon as I import Angular 2 into a file none of my tests execute. Question: How can I set up my karma config to support angular two so my test pass properly? OR Question: How can I set up any testing framework with angular2 written in es6? Git...

How do I test array element types using BDD Javascript?

javascript,unit-testing,bdd
I am writing a Javascript unit test using the BDD style. I want to test that a value is an array has all string elements I can get the first condition with value.should.be.an('array'); Is there a way to test for the second condition using this idiom?...

How can I test my Struts 1.2 web application without server?

java,unit-testing,spring-mvc,struts-1
I have a Struts 1.2 web application. It has service & DAO classes as well. How can I test each and every layer without any Web/Application server. I heard, Spring provides the same facility for Spring MVC application. How I can test my application end to end? Please suggest?

Unit testing ASP.NET Web API 2 Controller which returns custom result

c#,.net,unit-testing,asp.net-web-api,asp.net-web-api2
I have a Web API 2 controller which has an action method like this: public async Task<IHttpActionResult> Foo(int id) { var foo = await _repository.GetFooAsync(id); return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css); } Where CssResult is defined as: public class CssResult : IHttpActionResult { private readonly string _content;...

unit test on exception

c#,unit-testing,visual-studio-2013
I'm writing a unit test, where by I pass in a model and the title field in particular is required. My test is as follows: [TestMethod] [ExpectedException(typeof(Exception), "Movie Title is mandatory")] public void Create() { var mc = new MoviesController(); var model = new Movie { Cast = new[] {...

How to make mocha fail when no expect within it()

unit-testing,tdd,mocha,karma-mocha,mocha-phantomjs
Is there an option to set mocha to report test as failing in case no expect provided within it() function? Idea is workflow to be like this: add one it() with desc and callback function the it() is reported as fail since no expectation is set in the callback expectation...

Expressive assertion failure messages in C++

c++,unit-testing,assertions,verbosity
Unit test frameworks generally provide very nice assertion failure messages (I'm using gtest) describing expected and actual values to a particular test. Furthermore, you know the origin of the function call because you're testing the interface of the class. In contrast, assert, when used as a sanity check in the...

how to mock $state.params in jasmine unit testing

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following controller EditMeetingCtrl.js (function() { 'use strict'; angular .module('myApp') .controller('EditMeetingCtrl', EditMeetingCtrl); EditMeetingCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$translate', 'meetingService', 'companyService', 'notificationService', 'meeting']; function EditMeetingCtrl($rootScope, $scope, $state, $http, $translate, meetingService, companyService, notificationService, meeting) { $scope.meeting = meeting; $scope.companyId = $state.params.companyId; $scope.save = save; function...

Dependency injection in JavaScript using apply, call or bind methods

javascript,unit-testing
I'm fairly new to JavaScript and have a question about unit-testing an object and it's methods. Is using the JavaScript bind, apply and call methods considered a form of dependency injection? I ask because I have several functions I want to unit-test that use the 'this' keyword and I would...

Visual Studio C# Unit Tests

c#,unit-testing,visual-studio-2013
I'm trying to learn Unit Testing in C#. But I don't see how to relate the testmethods to the actual methods. In one guide it told me to right click the method name and click create unit test. I don't see that. Another told me to create a Unit Test...

Using Q.js promise for unit-tests: timeout of 2000ms exceeded

javascript,unit-testing,asynchronous,mocha,q
I'm using Q.js library for simulating async behaviour by using promise I have a stubed backend api class ApiStub { constructor(){ this.deferred = Q.defer(); } post(url, data) { if (data) { this.deferred.resolve(data); } else { this.deferred.reject(new Error("Invalid data")); } return this.deferred.promise; } } and I'm trying to test it: before(()...

Test XML content without using mock mvc

xml,spring,unit-testing,xpath,spring-test
I am using spring test with mockmvc and it works like a charm to test xml output! Example: ResultActions actions = this.mockMvc.perform(get("/entry/NX_P38398/overview.xml")); actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").exists()); actions.andExpect(xpath("entry/overview/gene-name-list/gene-name[@type='recommended']").string("BRCA1")); I would like to take advantage of the same features to test an OutputStream without using mockmvc and controllers. Is it possible to use the same...

Faking Ajax Request Form for testing

java,ajax,unit-testing,playframework,playframework-2.0
In my Playframework 2.4 project I have methods like this: public static Result resetValue(int client) { String receivedName= form().bindFromRequest().get("username"); User user = User.findByName(receivedName); if( user == null ) { return badRequest("No user logged in"); } user.setValue(0); user.saveUsertoDB(); return ok("Value set to zero"); } I want to write JUnit Tests for...

How to unit test a data extraction method

php,unit-testing,phpunit
I have created a method which interacts with a framework, pulling out order items which have a completed status. However, how can I unit test my method to ensure it behaves correctly... class A { public function extractData() { // extract data from framework $dataCollection = FrameworkX->getDataCollection('sales/orders'); $dataCollection->filter('state', 'complete'); return...

nose reports cumulative coverage

python,unit-testing,testing,nose
Image a situation where you have a BASE_CLASS. Several class inherits from that class: CHILD_A, CHILD_B, CHILD_C. Now let us write unit tests, but ONLY for CHILD_A, CHILD_B, CHILD_C. I would suspect, that the coverage for BASE_CLASS is 0%. Unfortunately, nose takes cumulative coverage, which is not what I want....

NUnit Categories not showing up in Visual Studio

unit-testing,visual-studio-2012,nunit
I want to custom group my tests by function so I'm using the nunit Category attribute, like this: [Test, Category("Cat1")] public void SomeMethod() { } [Test, Category("Cat2")] public void AnotherMethod() { } But in Visual Studio the categories do not show up, all I see are the defaults to group...

Dependencies in Unit Tests

c#,unit-testing,nunit
From what I've read on the subject, each unit test should be independent and not rely on the results or success/failure of any other test. Makes good sense to me. How best to write tests that have dependencies then? Take the simple example like a file system that has a...

How to run single android unit test using gradle 2.4. Test filtering is not supported

java,android,unit-testing,android-studio,gradle
I'm using gradle to build my android project and am not able to run single unit test. I have several test classes and one of them is MockServerTest and I only want to run test methods in this class. I tried using gradle -Dtest.single=MockServerTest test but it turned out running...

MOQ object setup scope / context being lost with builder pattern unit test and web api controller

c#,unit-testing,moq
I am writing unit test for controllers and was running into an issue where it seems the Mocked object is not getting setup when I inject it. If however I create the Mocked object in the controller end point everything works fine. Finally to further complicate things I am doing...

Is it possible to use Mockito to completely stop a method from running?

java,unit-testing,mockito
I'm unit testing a method that has a lot of logic in it. It goes something like this: public void doSomething(int number){ //... complex logic if (number % 2 == 0) someInstanceObject.setOdd(false); else someInstanceObject.setOdd(true); //... more complex logic and database connections } Is it possible for Mockito to just end...

Mocking/Testing HTTP Get Request

java,unit-testing,http,junit,mockito
I'm trying to write unit tests for my program and use mock data. I'm a little confused on how to intercept an HTTP Get request to a URL. My program calls a URL to our API and it is returned a simple XML file. I would like the test to...

What should I annotate when I unit test the GPS function with Robolectric?

unit-testing,annotations,robolectric
I am referring the following site http://googletesting.blogspot.ca/2010/12/test-sizes.html . There it was mentioned that we should annotate @LargeTest if our test method is accessing the network feature. I am using Roboloectric for unit testing. And my method uses the shadowLocationManager to simulate the GPS location. I am not sure what should...

Unit Testing VSTO projects

c#,unit-testing,vsto
In most unit test tutorials I follow it has me create a second unit test project and then add a solution/project reference from the test project to the other project. I have a VSTO addin, and when I go to add the reference I don't see anything listed under Solution...

Visual Studio 2012 - Fill message test result

c#,asp.net,unit-testing,visual-studio-2012,testing
When a test end its running i have a list like this Result1 Name: 01- AutoGenerateRequest (requestgenerationtest) Result1 Outcome: Passed Result1 Duration: 0:00:26,2924949 Result1 Message: Result1 StackTrace: how can i write something in the result message or stacktrace?...

Using mock to test a void method

.net,unit-testing,moq,xunit
I have a class public class NLogRuleComposer : INLogComponentComposer { private LoggingConfiguration _nLogLoggingConfiguration; //TODO: think we need to constructor-inject the logging config public void ComposeComponent(LoggerModel loggerModel , LoggingConfiguration nLogLoggingConfiguration , string loggerFullName) { _nLogLoggingConfiguration = nLogLoggingConfiguration; var ruleName = loggerFullName; var minimumLevel = LogLevel.FromString(loggerModel.level.min_level); var maximumLevel = LogLevel.FromString(loggerModel.level.max_level); var...

How to check http status code in python version agnostic way?

python,unit-testing,httplib,test-coverage,http.client
I'm writing python code that should run both with python 2.7 and 3.3+ I'm trying to figure out a way to properly check for http status codes and don't reduce my test coverage %. if I write something like: try: import http.client as httpclient except ImportError: import urllib as httpclient...

Why are nUnit tests just getting ignored when using TestCaseSource?

c#,.net,unit-testing,nunit
I am having a lot of difficulty getting the nUnit TestCaseSource attribute to work correctly in nUnit 2.6.4.14350. When running the unit tests through VS2010, it just says the tests are being ignored, without any additional information as to why. The Create test just appears greyed out on the test...

Only function definitions covered by unit testing python/flask backend

python,unit-testing,flask
I would like to start by saying that i am a beginner at both flask and unit testing in Python, so bare that in mind. I am writing some unit testing for a backend that I am building for an android app. I am trying to write tests for the...

Select out auf

javascript,jquery,html,angularjs,unit-testing
I'm testing a directive which cuts off text after 200 characters. It transforms this: <span mw-text-collapse="long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long...

Rx.js React extension testing stream and intermediate results

unit-testing,reactjs,rxjs
I have a module which stores data in this.store and takes keyboard events in this.stream The relationship between this.store and this.stream is as follows this.stream.subscribe(function(keyCode){ this.store.add(100) }); Now I am writing test cases against those events. I want to know when I click the keyboard 3 times respectively what will...

Flask jsonify boolean response cannot be decoded in unit tests

python,unit-testing,flask
I am performing tests on my Flask application and I am expecting a json response built with jsonify. I use the ast library to decode the response. But I am getting the following error: Traceback (most recent call last): File "test_index.py", line 177, in test_create_venue data = ast.literal_eval(rv.data) File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py",...

How can I send a function to another thread?

multithreading,unit-testing,rust
I am attempting to write a simpler unit test runner for my Rust project. I have created a TestFixture trait that my test fixture structs will implement, similar to inheriting from the unit test base class in other testing frameworks. The trait is fairly simple. This is my test fixture...

Using Robolectric, how to init and finalize stuff before and after all test methods in a test class is ran

java,android,unit-testing,robolectric
I'm using Robolectric to do unit testing. I have a test class say MainActivityTest, which has several test methods: @RunWith(...) @Config(...) public class MainActivityTest { @Test public void testMethod1() { //... } @Test public void testMethod2() { //... } // other test methods } I want to execute a method(init...

How to unit test the GPS location in android using Robolectric?

java,android,unit-testing,robolectric
I have an android app that gives the current location when button is tapped. I want to unit test this functionality . I'm using Robolectric . The issue is ,the system services are accessed in onCreate() method but not out of it. If that is the case,how can I access...

How to Mock an object which is created in the class under test in Mockito

java,unit-testing
I need to mock an object which is instantiated from the method under test. Please check the below code for your reference. Class Under Test: package org.sambaran.model; import java.util.List; public class Book implements Item { private String isbn; private String title; private String description; private List<Author> authors; private BSOInterface bsoInterface;...

How to properly unit-test a linked list (using Python)?

python,unit-testing,linked-list
I'm new to TDD. I've created all the main functions (insert, search, remove etc.). This is my insert_beginning() function: def insert_beginning(self, node): ''' Inserts a Node to the beginning of the list. ''' node.set_next(self.head) self.head = node My question is, how do I properly unit-test this function? The only way...

Rspec view test with url parameters

ruby-on-rails,unit-testing,testing,rspec,rspec-rails
I have a page dashboard.html.erb that may be redirected to from several different controllers/actions. When it receives the redirect, it also receives several url parameters. Controller code: class PlansController def some_action redirect_to dashboard_path(show: "default", cool_array: ["test", "test"]) end end class StaticpagesController def dashboard end end View code: <% if cool_array...

Mocked repository does not trigger as expected

spring,unit-testing,mocking,mockito,mockmvc
I have a Controller Unit test using Mockito and MockMvc. After a POST request, the POSTed object is resolved correctly, but my repository mock is not triggered. Here is the mock code: Date mydate = new Date(); Notification not = new Notification(); not.setId(-1L); not.setUserid("BaBlubb"); not.setTimestamp(mydate); not.setContent("MyContent"); Notification not2 = new...

Accessing scope.variables inside a function in jasmine

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I am trying to get the assert the value of the $scope.buttonDisable variable which is inside the save(). here is the test case describe('EditMeetingCtrl.save()', function () { var $rootScope, scope, $controller , $q , state , controller ; var companyService , meetingService ; beforeEach(angular.mock.module('MyApp')); beforeEach(angular.mock.inject(function (_$httpBackend_, _companyService_ , _meetingService_ )...

Unit testing: bypass or mock call to static email helper

c#,unit-testing
Apologies - this is a likely duplicate. But I was unable to find a useful answer elsewhere on the site. Currently working on adding email-sending functions to an application. It's not been done under TDD but we've built the tests as we go along and have good coverage. My task...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing
I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

Can I pass VisualStudio Edition name through a compiler option?

c#,visual-studio,unit-testing,vs-unit-testing-framework,compiler-options
I am using Microsoft.QualityTools.Testing.Fakes to mock some unit tests. But this assembly is only available to users with VisualStudio Ultimate. Users with other editions (Professional) can't build and run this test project, and it gives an error on their environments. So I have created a compiler directive to deal this:...

Testing beforeFilter() function

php,unit-testing,cakephp-3.0
I am doing unit testing for a PHP application using CakePHP framework. The function that I am testing is beforeFilter() which basically loads the models. public function beforeFilter(Event $event) { parent::beforeFilter($event); $this->loadModel('Model1'); $this->loadModel('Model2'); $this->loadModel('Model3'); $this->loadModel('Model3'); } How should I test this function ? What assertions I need to make in...

How to simulate error returned from fs.readFile for testing purposes?

node.js,unit-testing,mocha,fs,chai
I am new to test-driven development and am trying to develop an automated testing suite for my application. I have successfully written tests that verify the data received from a successful call to Node's fs.readFile method, but as you will see in the screenshot below, when I test my coverage...

Spring controller unit testing with spring-test-mvc is failing

java,spring,unit-testing,spring-mvc
I am learning unit testing of spring controller with EasyMock and Spring test framework. I have done a simple unit testing for my controller. import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import...

Ruby: How to refer to classless script while using Test::Unit?

ruby,unit-testing
I am new to Ruby, just picked it up last week. Currently using Ruby 2.0. Thus far I've just been looking up methods and googling for problems I've run into, which has been going well, but now I've stumped onto something that google does not seem to have an answer...

I have to make a method public and virtual to using Moq Setup

c#,unit-testing,moq
I have a repository that has a few private methods in to help in some general stuff that needs to be done within that repository (don't feel you need to read all the code): public class EFBlogRepository : EFGenericRepository<Blog>, IBlogRepository { public EFBlogRepository( EFDbContext context ) : base( context )...

JUnit Tests: Why is Maven (Surefire) so much slower than running on Eclipse?

java,maven,unit-testing,junit,spring-test
I'm working on a fairly big application, with ~260k LOC and roughly 1800 unit tests on the suite. A little background: Multi-modular Maven project All tests run on a separate module and JaCoCo is used to check coverage. Tests are put together in some suites and then the suites are...

Mockito: get the value of a field in a mocked object

java,unit-testing,mockito
I have a mocked javax.ws.rs.client.WebTarget webTarget. Then I do following: Mockito.when(webTarget.path(Mockito.anyString())).thenReturn(webTarget). Now I'd like to retrieve the String set during the .path(String) method out of the webTarget mock. Is there any chance I can do that? At the time webTarget.getUri() unfortunately returns null....

Testing an RSpec mock that is called twice

ruby-on-rails,ruby,unit-testing,rspec
I have a validation module that I include in my controllers. In my controllers for Admin actions they all inherit from an AdminController which calls require_permission :admin before each to make sure the current user is an admin. In another one of my controllers I call require_permission? :view_admins to verify...

When should I use the .As method of Moq?

c#,unit-testing,moq
When exactly do we need to use the .As method provided by Moq? From the Quickstart documentation: // implementing multiple interfaces in mock var foo = new Mock<IFoo>(); var disposableFoo = foo.As<IDisposable>(); // now the IFoo mock also implements IDisposable :) disposableFoo.Setup(df => df.Dispose()); But I just don't get why...

What is the difference between User.make and User.new?

ruby-on-rails,unit-testing,rspec,capybara
In Capybara docs, it has describe "the signin process", :type => :feature do before :each do User.make(:email => [email protected]', :password => 'password') end it "signs me in" do visit '/sessions/new' within("#session") do fill_in 'Email', :with => [email protected]' fill_in 'Password', :with => 'password' end click_button 'Sign in' expect(page).to have_content 'Success' end...

Unit Testing Synchronous Method With Code Calling Task

c#,.net,multithreading,unit-testing
Given the following class: public class TestAttribute : ActionFilterAttribute { public bool SomeExampleBool = false; public override void OnActionExecuting(HttpActionContext actionContext) { Task.Factory.StartNew(() => { SomeExampleBool = true; }); } } How would you write a valid unit test for OnActionExecuting that Asserts that SomeExampleBool is equal to true? When writing...

How to override some property in the class under test during unit testing

c#,unit-testing,design-patterns
I have a class that I would like to test with Unit tests. It has some logic to look for some values in the local xml file, and if the value is not found it will read some external source (SqlServer DB). But during Unit testing I don't want this...

How to mock.patch a class imported in another module

python,unit-testing
I have a python class with such a module: xy.py from a.b import ClassA class ClassB: def method_1(): a = ClassA() a.method2() then I have ClassA defined as: b.py from c import ClassC class ClassA: def method2(): c = ClassC() c.method3() Now in this code, when writing test for xy.py...

Unit and integration tests organization in .net

c#,.net,unit-testing
What is the best practice on organizing both Unit AND Integration tests in your solution? I am leaning towards having 2 test projects per one actual project with naming such as ProjectName.Tests.Unit and ProjectName.Tests.Integration, however it looks like there will be too many test projects per code projects. However the...

How to setup Request.Header in FakeHttpContext for Unit Testing

c#,unit-testing,asp.net-web-api,httpcontext
I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id",...

Swift unit test - unexpectedly found nil while unwrapping an Optional value

ios,swift,unit-testing,optional
I am trying to write a unit test which is resulting in this error fatal error: unexpectedly found nil while unwrapping an Optional value When I run my tests normally (Command-U) then it fails on this line in my ViewController (outside of my tests) songTitleTextField.placeholder = "Enter your song title...

How stub a global dependency's new instance method in nodejs with sinon.js

javascript,node.js,unit-testing,sinon
Sorry for the confusing title, I have no idea how to better describe it. Let's see the code: var client = require('some-external-lib').createClient('config string'); //constructor function MyClass(){ } MyClass.prototype.doSomething = function(a,b){ client.doWork(a+b); } MyClass.prototype.doSomethingElse = function(c,d){ client.doWork(c*d); } module.exports = new MyClass(); Test: var sinon = require('sinon'); var MyClass = requre('./myclass');...

Nsubstitute, changing the value of a property which is substituted

c#,unit-testing,mocking,xunit,nsubstitute
I would like to mock a property in my model to a specific value (because it has a private setter). Then I would call a method which changing this property and then check result. The problem is that the property would always return this value. Can I somehow get around...

Fake calling Namespace to test reflection

c#,unit-testing,nunit,system.reflection
I have a piece of code that gets a specific portion of the namespace from the calling assembly. Now I want to unit test this code. Is there a way to fake the name of the calling namespace using NUnit without implementing the NUnit testcase in that particular namespace? Here...

How can I verify that RemoveRange has been called on a mock DbContext?

c#,entity-framework,unit-testing,moq
I am using Moq to test code that calls RemoveRange on a DbSet<T>. I have mocked the context object and DbSet, but when I attempt to Verify that RemoveRange was called, I get "Expected invocation on the mock once, but was 0 times." The method I'm testing has this code:...

Robolectric 3 : Load test specific resource

android,unit-testing,robolectric
I'm using Robolectric 3 and I'm trying to load some resources that are in my test/res/ folder. Here is my file hierarchy : project/ |-src/ |--main/ |---AndroidManifest.xml |---res/ |----raw/ |-----prod.json |--test/ |---java/ |----com.app/ |-----CustomTestRunner.java |-----Mytest.java |---res/ |----raw/ |-----test.json I would like in MyTest.java to do something like RuntimeEnvironment.application.getResources().openRawResource(R.raw.test); but i...

Python unittest - possible to keep failing until pass?

python,unit-testing,python-unittest
Let's say there is a test function that goes through a list of various numbers to test. These numbers are listed in increasing order such that once you get past a certain number (done through a loop), the results become acceptable and I can pass the test. (This means that...

Testing a class in phpspec involving Guzzle

unit-testing,guzzle,phpspec
I'm trying to build a class that queries an external API. Each method that corresponds to an endpoint makes a call to a 'master call' method responsible for actually sending a request to the API. For example: // $this->http is Guzzlehttp\Client 5.3 public function call($httpMethod, $endpoint, array $parameters = [])...

Why mocking a private method enters method?

java,unit-testing,powermockito
I'm using PowerMockito to mock a private method in my test. validator = spy(new CommentValidator(form, request)); PowerMockito.when( validator, method(CommentValidator.class, "isCaptchaValid", HttpServletRequest.class)) .withArguments(Mockito.any()) .thenReturn(true); When I run the test I get java.lang.reflect.InvocationTargetException with a NullPointerException at the second line of the isCaptchaValid method, which looks like this: private boolean isCaptchaValid(HttpServletRequest request)...

Spock Framework: problems with spying

java,unit-testing,groovy,spock,spock-spy
I have an issue with using Spy in Spock, it either doesn't work as it should or my understanding is wrong so I'm trying to clarify this. Consider this code (Java): public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one...

Ember CLI generated unit test is failing on it exists

javascript,unit-testing,ember.js,ember-cli,ember-qunit
I have an order controller in controllers/order.js import Ember from 'ember'; export default Ember.Controller.extend({ needs: "orders" }); This has a test in /tests/unit/controllers/order-test.js import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:order', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this...

Unit testing a fluent interface with Mockito

java,unit-testing,mocking,mockito,builder-pattern
I want to mock the DAO interface used in the builder pattern as shown below. However when I run the test below it passes indicating that my mock object is never called. What am I doing wrong? public class DBContent { ... public static class Builder { DAO dao =...

Node unit tests - TypeError: Cannot read property 'order' of undefined

node.js,unit-testing,proxyquire
I'm getting the following error, Error: BLANKET-Error parsing instrumented code: TypeError: Cannot read property 'order' of undefined in my test code indicating the line where testedModule = proxyquire('../index', {. Can anyone see why I am getting this error? My test file: pattern: function (filename) { return !/node_modules/.test(filename); } }); //...

Laravel 5.1 Unable to Run Test on User Password Mutator

php,unit-testing,laravel,phpunit,laravel-5.1
I have a password mutator: /** * Mutator for setting the encryption on the user password. * * @param $password */ public function getPasswordAttribute($password) { $this->attributes[ 'password' ] = bcrypt($password); } That I'm trying to test: /** * A basic check of password mutator. * * @return void */ public...

JUnit tests pass but PIT says the suite isn't green

java,unit-testing,mutation-testing,pitest
While trying to run a PIT mutation test I get the following error: mutationCoverage failed: All tests did not pass without mutation when calculating line coverage. Mutation testing requires a green suite. The tests run just fine when I do a normal test build but while running the mutation tests...

How to test Dart Polymer elements using the new Test library?

unit-testing,testing,dart,dart-polymer
How do you test Polymer elements using the new test library? Using the new test library to test a Dart Polymer element, I build my_element_test.html as prescribed. Please see my repo: polymer-dart-testing. No Polymer Initiation Passes my_element_test.html and my_element_test.dart (commenting out Polymer initiation) passes tests as expected: my_element_test.html <!doctype html>...

How can I unit test a controller in an AngularJS Directive?

javascript,angularjs,unit-testing,angularjs-directive,karma-jasmine
My directive is: window.map.directive('dosingFrequencies', [ function() { return { restrict: 'E', scope: true, templateUrl: '/views/directives/dosingFrequencies.html', controller: function($scope, util) { console.log('here we go!'); angular.extend($scope, { model: createModel(), addFrequency: function(med) { med.frequencies.push(createFreqModel()); }, removeFrequency: function(med, index) { med.frequencies.splice(index, 1); }, showTimeChecked: function(freq) { if (freq.showTime) { freq.prn = false; freq.quantity = '';...

How can I get simulated react events to update the values of the ref in my component?

javascript,unit-testing,testing,reactjs,reactjs-testutils
So I have a react component that looks something like this: class SignInForm extends React.Component { constructor(props) { super(props); } onFormSubmit(event) { const username = React.findDOMNode(this.refs.username).value; const password = React.findDOMNode(this.refs.username).value; // very basic validation if (username && password.length > 6) { this.props.flux.signIn({ username, password }); } event.preventDefault(); } render() {...

Change name of NUnit test

c#,.net,unit-testing,nunit
I want my unit-tests based on NUnit framework named a bit more human readable in Visual Studio test explorer. For example instead of having Test_Case_1 or TestCase1 I would better have something like Test Case #1, Category: First, Category: Second (by assigning values from [Category] attributes as well), with spaces...

java test objects with static field

java,unit-testing,static
I have the object with static field: class Project() { private static id; private int projectid; public Project(fileds) { this.id = id++; } //methods } Now I want to test this class with multiple tests. The problen is that my objects are not deleted from memory when one test is...

Symfony2 Functional Testing: Is a database required or not?

php,unit-testing,symfony2,doctrine2,functional-testing
I have to write functional tests for a controller that registers a user in the application. The controller has two methods (and routes): registrationAction (route=registration) endAction (route=registration/end) Now I would like to write functional tests for those two methods. My question is: as the controller creates and persists a new...

Cakephp 3 - MissingDatasourceConfigException when running phpunit test

php,unit-testing,cakephp,phpunit,cakephp-3.0
I am trying to run some unit tests in CakePHP 3 with PHPUnit 4.7.3, but I`m getting the following error: PHPUnit 4.7.3 by Sebastian Bergmann and contributors. There was 1 error: 1) App\Test\TestCase\Model\Table\MoviesTableTest::testFindMoviesByGenre Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found. C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\Datasource\ConnectionManager.php:188 C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\ORM\TableRegistry.php:191...

Selenium C# Element Not Found Taking a Long Time

c#,unit-testing,selenium,selenium-webdriver
I am using Selenium for C# to test a page. Is there a way to quickly fail if the element is not found on the page? I am experiencing if the HTML element is not found on the page the Selenium test a very long time and then eventually it...

'Module was not compiled for testing' when using @testable

ios,swift,unit-testing,swift2
I'm trying to use Swift 2's new @testable declaration to expose my classes to the test target. However I'm getting this compiler error: "Intervals" is the module that contains the classes I'm trying to expose. How do I get rid of this error?...

How do I mock multiple levels of DbSet.Include lambdas?

entity-framework,unit-testing,lambda,moq
I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

How do I stub and spy at the same time

javascript,angularjs,unit-testing,mocha,sinon
So I'm testing a function that calls another function, that returns a promise, SUT looks like this: fn($modal) -> modalInstance = $modal.open({ controller: 'myCtrl' size: 'lg' }) modalInstance.result.then(updateData) now If I need to test it I could start with something like this: it 'when modal called, results get updated with...

How to mock a Android NFC Tag object for unit testing

android,unit-testing,android-intent,mocking,nfc
I'm currently working on an Android project which needs NFC integration. Now I want to write some (j)unit tests to see if the application can receive NFC intents (specifically ACTION_TECH_DISCOVERED) and put the given tag (in NfcAdapter.EXTRA_TAG) on a bus system. However to my surprise I cannot create a Tag...

configuration of karma/jasmine to test angularjs throws: No provider for “framework:jasmine”!

angularjs,unit-testing,karma-jasmine
Hello I'm trying to implement unit-tests for angularjs with karma and jasmine. I followed therefore this tutorial: http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing On the point Running Your First Test I get sucked because of an error: No provider for "framework:jasmine"! I googled for it and tried the suggested things like installing karma-jasmine and karma-chrome-launcher...

Testing a function with several side effects [on hold]

unit-testing
Consider this (bash) function which has several side-effects (setting a global variable, printing to stdout): describe() { printf '\n%s\n' "$1" skip_specs=false } It prints to stdout and sets the value of the global variable skip_specs. What are the pros/cons of: one test per side-effect one test for both side-effects ...

Unit testing OCaml modules with pa_ounit

unit-testing,ocaml,ounit
I have a simple module to test with a few inline pa_ounit tests, i've setup the directory in the oasis style and got it all to build. For a reference I've been using: https://github.com/janestreet/textutils How would one execute the unit-tests for the above repo? I'm assuming there's an executable .ml...

How detailed should your repository be? Testing issues [closed]

c#,unit-testing,asp.net-mvc-5
In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

Python Mocking of Boolean Function

python,django,python-2.7,unit-testing,mocking
So I have just begun working with the mock library to perform some unit testing. But ran across a problem that is certainly mysterious to me. When I call the below code stream.open() always evaluates to True, as it seems to be returning the Mock object rather than the False...

Nunit runsTestCase with a TestCaseSource with the first iteration having no parameters? Why?

c#,unit-testing,nunit,testcase,testcasesource
Hi I am new to Nunit and I am passing a series of objects to a TestCase as a TestCaseSource. For some reason though Nunit seems to run the test first with no parameters passed to it which results in an ignored output: The test: private readonly object[] _nunitIsWeird =...

Unit test a void method with Mock?

c#,unit-testing,moq,xunit
I want to test a void method with Mock. public class ConsoleTargetBuilder : ITargetBuilder { private const string CONSOLE_WITH_STACK_TRACE = "consoleWithStackTrace"; private const string CONSOLE_WITHOUT_STACK_TRACE = "consoleWithoutStackTrace"; private LoggerModel _loggerModel; private LoggingConfiguration _nLogLoggingConfiguration; public ConsoleTargetBuilder(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration) { _loggerModel = loggerModel; _nLogLoggingConfiguration = nLogLoggingConfiguration; } public void...

How to capture field value when a method of a class is called in Python?

python,unit-testing,mocking
I have a weird 3rd party library that requires me doing the following (A is imported from that library): def foo(my_props): a = A() a.props = my_props a.post() So what I want is to make sure that when a.post() is called, its props are set correctly. Note that this is...

Wrong type of error when testing javascript function

javascript,unit-testing
I am trying to test the following code: /** ABSTRACT METHOD PLACEHOLDER */ MyResult.prototype.get = throwNotImplementedError; function throwNotImplementedError(resultId) { throw new NotImplementedError('Please implement in Item Groups and Items. This call is abstract'); } with the following test. it('should have a placeholder for get', function(){ expect(function(){return MyResult.get(123);}).toThrowError(NotImplementedError); }); What ends up...

Python AttributeError in Testing Goat

python,unit-testing,selenium
I've just started working through Test-Driven Development with Python and don't understand the AttributeError I'm getting as it's different from the one in the book. The code to run a selenium test is: from selenium import webdriver import unittest class new_visitor_test(unittest.TestCase): def set_up(self): self.browser = webdriver.Firefox() def tear_down(self): self.browser.quit() def...

managed object context nil restkit while unitTesting

swift,unit-testing,restkit,cocoapods,nsmanagedobjectcontext
I am developing unit tests for my application using restkit (0.24.1) integrated using cocoapods: pod "RestKit/Testing", "~> 0.24.1" pod "RestKit", "~> 0.24.1" I am getting a error message saying that the managedObjectContext is nil. I beg to differ because I already have lots of unit tests using the same object...

Can I pass type parameters to a testcase in DUnitx?

unit-testing,delphi,generics,dunitx
I'm writing testcases for my FastCode project. I've written a generic tester like so: TTest<T> = record private class var Def: System.Generics.Defaults.IComparer<T>; class var F: FastDefaults.TComparison<T>; strict private class function Slow(const Left, Right: T): integer; static; class function Fast(const Left, Right: T): integer; static; class constructor Init; public class procedure...

Mock the value of a service inside directive's unit test

angularjs,unit-testing,jasmine,karma-runner
Inside my directive's instantiation I have a call to a method that returns some data: data = myService.getData() and later in the code I am doing something = data[id] In karma I have an error, cannor read id of undefined, meaning that data is undefined. I tried to mock the...

How to mock a window.location function in Karma/jasmine

angularjs,unit-testing,karma-jasmine
I would like to mock a functionality in Karma who returns a file after clicking a download button. I have the following AngularJS controller: var secure = angular.module('secure', []); secure.controller('ProcedureController', ProcedureController); ProcedureController.$inject = ['$controller', '$rootScope', '$scope', '$http']; function ProcedureController($controller, $rootScope, $scope, $http) { ... // Controller does more stuff var...

Stubbing WinBase.h in cppunit test

c++,unit-testing,named-pipes,cppunit
I'm writing a unit test for a class that uses named pipes. I need to stub CreateNamedPipe, ConnectNamedPipe, WriteFile, ReadFile, FlushFileBuffers, DisconnectNamedPipe, CloseHandle, and GetLastError These are all defined in WinBase.h as dll imports. Unfortunately WinBase.h is a gigantic file that's used everywhere, so one can't merely stub out the...