Unit testing Blocks of similar text for test data

For testing purposes I need to create sets of text files that have similar but not identical text. Each set needs to be different from the other set but also share some commonality. For example, I may need to create 10 sets of 20 documents each for a total of 200 documents. Each document needs about 250 words in it. If one of the sets of documents is about dogs then it would be appropriate that the other sets' documents be about animals, for example, such that there is a weak link between each

Unit testing Testing a card deck shuffler

I have a class PlayingCard which represents a particular playing card. I have another class, Deck, which contains a list of PlayingCard objects. Deck has a shuffle() method that randomizes the card order. I would like to write some unit tests for the shuffle() method, but I'm at a bit of a loss. I'd prefer the test to not care about the internals of just how the shuffle is done, but I want them to be good tests. How do I best unit test when randomness is involved?

Unit testing How to unit test the sorting of a std::vector

I have never used unit testing before, so I'm giving CxxTest a go. I wrote a test to check if a function correctly sorts a std::vector. First I made sure the test failed when the vector wasn't sorted, and then as a sanity check I tested whether std::sort worked (it did, of course). So far, so good. Then I started writing my own sorting function. However, I made a mistake and the function didn't sort correctly. Since my test didn't output the intermediate states of a vector as it was being sorte

Unit testing How to use "Pex and Moles" library with Entity Framework?

This is a tough one because not too many people use Pex & Moles or so I think (even though Pex is a really great product - much better than any other unit testing tool) I have a Data project that has a very simple model with just one entity (DBItem). I've also written a DBRepository within this project, that manipulates this EF model. Repository has a method called GetItems() that returns a list of business layer items (BLItem) and looks similar to this (simplified example): public IList&l

Unit testing Using Clojure to unit test Java

One of the ways to get an organization to accept an alternate JVM language is to first use it for unit testing Java code -- "Boss, I am just going to write some unit tests in XXX. It'll never go out into production." Are there any tutorials for doing this in Clojure? I have just started using Scala to do this to test a Java REST server. Writing the tests in Scala allows me to embed expected XML output, mock the database calls with literal List objects, etc., not to mention that traits make it

Unit testing What is the best way to unit-test SLF4J log messages?

I'm using slf4j and I want to unit test my code to make sure that warn/error log messages are generated under certain conditions. I'd rather these be strict unit tests, so I'd prefer not to have to pull up logging configuration from a file in order to test that the log messages are generated. The mocking framework I'm using is Mockito.

Unit testing How to unit test a Django South "datamigration"

I created a data migration using south, that takes a versions table and converts it from: major: 1, minor: 2, micro: 3, release: a into a simpler: name: 1.2.3.a Now I want to test this datamigration using django unit testing (1.3beta). How can I use south programatically to roll migrations forward and backward while specifying custom fixtures to use that I can validate?

Unit testing White-Box/ Black-Box Testing: static or dynamic?

Here is what I understand: Dynamic testing is testing that is performed when the system is running. Static testing is performed when the system is not running. Black-Box testing focuses on functionality and is performed without knowing the internal workings of the program. White-Box testing looks for problems within the code itself. What I am wondering is, Is it fair to say that all Black-Box testing is static? Is it also fair to say that some White-Box testing is static (for example, inspect

Unit testing Building a report against TFS showing number of unit tests linked to a requirement?

Is there a way to build a report using the MS Team Foundation Server API or other means so that I can count the number of unit tests which have been written against a requirement? ( or user story ) Approaches under consideration: (1) Create an attribute on test methods so we can note the requirement ID on the unit test method. Under this option, I am not sure how we could walk the test results and grab the requirement ID. (2) Put the requirement ID into the test method name (Ugly) (3) Start

Unit testing OCUnit: How to run tests without launching iPhone simulator?

I'm following iOS Development Guide: Unit Testing Applications. However, when I attempt to build (Command+B) the LogicTests target (step 8 of "Setting Up Logic Testing"), I get the error: "The selected run destination is not valid for this action." Since I added my application target to LogicTests's target dependencies, I'm able to run the unit tests with Command+U, but this also launches the iPhone Simulator. To save time & resources, is it possible to run the OCUnit tests (both logic &am

Unit testing Should I test that methods are NOT called?

Let's say I have this code: [HttpPost] public ActionResult Edit(MyViewModel viewModel) { if (ModelState.IsValid) { _myRepository.SaveStuff(viewModel.Property1, viewModel.Property2); return RedirectToAction("MyAction", "MyController"); } else { return View("Edit", viewModel); } } This is ASP.NET MVC, but that's actually irrelevant for my question. The real point is that a method (SaveStuff) is called only when a requirement is met. Now I want to

Unit testing State vs Interaction based testing

Assume we have an Order class with a method called Approve. When this method is called, it checks certain conditions and either puts the Order in the state of Approved or throws an exception. In the service layer, we've got something like this: var order = _repository.Single(o => o.ID == orderID); order.Approve(); _context.SaveChanges(); // or _session.SaveChanges(); There are 2 ways to test this method and I'd like to hear your insight on this: Solution 1: Stub the repository to retur

Unit testing Linking Error with UnitTest++

I am getting an odd Unit Test ++ linking error using Xcode as my ide. Now I did set the project up with two targets. one target that will do the test the other will do nothing for now. Note I did link the library and ran the simple working example from the tutorial. and I compiled it using gcc 4.2.1 from macports. "std::string::c_str() const", referenced from: UnitTest::MemoryOutStream::GetText() const in libUnitTest++.a(MemoryOutStream.o) "std::basic_ostringstream, std::allocator >::s

Unit testing Gallio unit test startup code

This is going to be an amateur level question. Is there a way to add start up code to a test project that uses MBUnit I tried adding [TestFixture] and [FixtureSetUp] attributes to code that I wanted to run first, but unfortunately that didnt help.

Unit testing Testing constructor

My constructor sets property with data which loaded from database. How can I test if it really load data from db? I want %100 test coverage rate so I need test every piece of my code. <?php class PreferencesAdapter { private $_preferences = NULL; public function __construct() { ... $this->load(); ... } public function load() { ... $this->_preferences= DataFromDb(); } } ?>

Unit testing Windows phone project run tests

I am using WPToolkitTestFX in Windows Phone 8 project. So I am running tests with special page, where in constructor I got: this.Content = UnitTestSystem.CreateTestPage(); But if I want to run application, I need to change Navigation Page in WMAppManifest.xml. It is not good, because I often forgetting to change it back and pushing that WMAppManifest to source control system. Is it possible to create difference run configuration for WP8 project? One for application, another for tests?

Unit testing Ember.js Konacha sinon.fakeServer not doing anything

I've got an ember.js app set up, I'm using ember.js 1.0.0-rc4 and ember-data 0.13, I'm trying to get konacha setup with mocha.js similar to this https://github.com/dgeb/ember_data_example. My spec_helper.js //= require konacha_config //= require_tree ./templates //= require application_test //= require sinon //= require spec_utils // Sinon fake server var server; // Stub out Konacha.reset() Konacha.reset = Ember.K; // Prevent automatic scheduling of runloops. For tests, we // want to ha

Unit testing How can I simulate blur when testing directives in angularjs?

The problem I am trying to test some directives (code for both below). One of them is an "email" (called "epost" in the code(norwegian)) directive. The solution to this should work for all of them, so I am keeping it to this one for now. Technologies: Angularjs, Jasmine, Requirejs, (grunt & karma running in Chrome) The directive validates email addresses in two ways; on upshift and on blur. I can test the upshift without problems as you can see in the test below, but I can't figure out ho

Unit testing ReSharper unit tests pending indefinetely

first of all, I've never used unit tests with ReSharper before, so I don't know how to debug it. The problem is that if run MS unit tests by VS test explorer everything works fine, but if I run it through resharper's Unit Test Sessions it just does nothing and stays in a pending state, even with just one test starting with Assert.Fail. I am seeing no load on CPU or anything. I am using ReSharper with Visual Studio 11.0.50727.1 . Searches bring me many results with older versions, bu

Unit testing Grails Mocks: Decoupling Validation from Controller

I have a several grails controllers that I generated and modified slightly. I'm working with the generated unit tests and getting them to pass, but I think I'm doing it the hard way. This is what I have. package edu.liberty.swiper import grails.test.mixin.* import org.junit.* @TestFor(AttendanceController) @Mock([Attendance, Location, Reason, Person, LocCapMode, GuestContactMode, UserAccount]) class AttendanceControllerTests { def location def reason void setUp() { def capMode = new

Unit testing Integrating Visual Studio 2012 into Cruise Control.NET

I am trying to easily display unit test results and code coverage reports from Visual Studio 2012 into the CruiseControl.NET Build Reports. The pieces are the following: MSBuild - to build the project vstest.console.exe - to execute visual studio unit tests and code coverage tools via the command line custom console application to convert coverage report to XML My problem is how can I control the output name for the vstest.console.exe. I am not finding anyway to control this. My only solutio

Unit testing drone.io headless dartium testing

Can you run browser based unit tests for Dart on drone.io? my last failed build is here. I tried sudo start xvfb but I'm not sure how to point that to my index.html file that launches my unit tests, anyone know how to do this? I should say that I am in no way interested in any actual DOM testing but my library imports 'dart:html' so I can't run it in the basic dart vm only configuration.

Unit testing Windows 8 App in Visual Studio 2012 - NUnit Test Adapter sees unit tests but does not run them

I have a Windows 8 Store App with two projects within the solution - one project exclusively for tests. I have added NUnit and NUnit Test Adapter (https://www.nuget.org/packages/NUnitTestAdapter/1.0.0) for this through nuget. My tests are detected - but I cannot run or debug them. Looking at the test output window, I get the following error: Could not find test executor with URI 'executor://nunittestexecutor/'. Make sure that the test executor is installed and supports .net runtime version

Unit testing Maven surefire unittests pom configuration

I need to write 2 unit tests. The first one (say envVarTrueTest()) requires an environment variable (say INFO) to be set. I set this environment variable in surefire plugin properties in pom.xml as <configuration> <environmentVariables> <INFO>infovalue</INFO> </environmentVariables> </configuration> For the second unit test, the environment variable INFO should NOT have been set. I don't know how to unset the variable for the second test now

Unit testing DART - expectAsync does not work with httpRequest

I am trying to test if asynchronous call happens after httpRequest returns. Here is my code: ... var httpRequest = new HttpRequest(); httpRequest.withCredentials = true; httpRequest.open('POST', repositoryURL); httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); httpRequest.setRequestHeader("Authorization", auth); test('Asynch testing of getting Repositories', (){ var callback = expectAsync(() {repositoryListComplete(httpRequest);

Unit testing How to add new test to already configured ctest suite?

I have a c++ project which has a test suite with already configured scripts. if i run ctest -V it normally check all test available in a directory. I have written a new test and saved it in the same directory but if I run ctest -V -R newtest , i get the following message. UpdateCTestConfiguration from :/home/user/project/DartConfiguration.tcl Constructing a list of tests Done constructing a list of tests Checking test dependency graph... Checking test dependency graph end No tests were

Unit testing why are empty strings converted to null passing to the constructor of the domain object in Grails 2.4.0?

I'm new to Groovy and Grails. The Spock test for the domain object to test persist fails due to the empty string being converted to null. Here is the code. The domain object, class Todo { String name Date createdDate String priority String status static constraints = { priority blank: true } } The Spock specification, @TestFor(Todo) class TodoSpec extends Specification { void "test persist"() { when: new Todo(name: 't1', createdDate: ne

Unit testing How to mock a specific method of Grails Domain class?

I'm trying to test a service which calls method getUrl() on my domain class: Service class: PersonService { //WE WANT TO TEST THIS METHOD. String getPersonLink(Person person){ person.url } } class Person { static transient LinkGenerator grailsLinkGenerator String name String uniqueId static transients = ['url'] String getUrl() { grailsLinkGenerator.createLink(controller:'xyz', action: 'index', id: uniqueId) } } I get the NullPointerException (it fin

Unit testing When should I write the different kinds of tests in TDD?

There are different kinds of tests: unit, integration, functional, and acceptance. So if I'm doing proper test-driven development, when do I write each kind of test? I'm thinking that in typical TDD, the unit tests are the kind of tests that precede the writing of code. The typical workflow I see is: Write failing unit test Run test to verify that it fails Write simplest passing function/method Run test to verify that it passes Refactor code Soooo...where do the integration, functional, and

Unit testing Is it possible to add test failures using a junit run listener?

I have a simple JUnit RunListener that checks whether a test case modifies some shared state (otherwise the next test case may not start expected state). public class SharedStateVerifier extends RunListener { @Override protected void testFinished(Description description) throws Exception { if (sharedStateHasBeenModified()) { throw new RuntimeException("The test case " + description.getDisplayName() + " has modified the shared state"); } } }

Unit testing Swift collections in unit tests

I am new to swift and I don't understand the implicit type casting, I have this in a unit test: let protocols: AnyObject? = NSBundle.mainBundle().infoDictionary?["UISupportedExternalAccessoryProtocols"]; I need test that protocols exists, is an array and contains "foo" and "bar".

Unit testing Blackbox-tests vs. whitebox

I´ve read here that black-box-testing (testing just the API without implementation-details) is prefered in most situations. However if I write only black-box-tests where I do not care for the actual implementation from where do I know how to handle any dependencies of the method to test? Imagine we make a database-call in our method to test. Usually I would fake that call in a way that allways returns some fake data in order to test if my own method handles that data accordingly. Within my test

Unit testing Polymer. How to unit test filter function

I'm using Polymer. I have simple filter function: _queryFilter: function(query){ return function(field){ if (!query) return true; if (!field) return false; return (field.name && ~field.name.indexOf(query)); }; } This is element: <input type="text" placeholder="filter" value="{{filterVal::input}}"> <template is="dom-repeat" items="{{fields}}" filter="{{_queryFilter(filterVal)}}"> {{item.name}} </template> I want to unit test it this way:

Unit testing Assert-MockCalled vs Assert-VerifiableMocks in Pester

What makes Assert-VerifiableMocks different from Assert-MockCalled in Pester? I've been reading https://github.com/pester/Pester/wiki/Assert-VerifiableMocks https://github.com/pester/Pester/wiki/Assert-MockCalled but still wonder: are the following sections of code equivalent and interchangeable? Using Assert-MockCalled: Mock Invoke-MongoCommmand {} Set-TargetResource -UserName $test_username -Ensure "Absent" Assert-MockCalled Invoke-MongoCommand -ParameterFilter { $Expression -eq "db.

Unit testing Mocking Reflux.js store during React component shallow rendering in test with enzyme

I'm writing React application. I want to test in isolation component that is wired up with Reflux.js store with: mixins: [ Reflux.connect(CountriesStore) ], Initialization code of CountresStore calls action that tries to fetch list of countries. This is the stop where some exception is being raised. But I feel that all this fuzz should not occur. I want to conduct unit, not integration testing. So, Is there a way to mock this CountriesStore prior of it being called during initializat

Unit testing Test to check if a function didn't run?

So I'm new to testing in general and I'm stuck trying to write a test for a function that triggers another function. This is what I have so far but it's kind of backwards and blocks forever if the function doesn't run: var cha = make(chan bool, 1) func TestFd(t *testing.T) { c := &fd.Fdcount{Interval: 1, MaxFiles: 1} c.Start(trigger) if <- cha { } }

Unit testing Mock property setter

I would like to mock a property setter in my test, but I can't find anything on how one does it. Here is what I have tried so far: interface Foo { var property: Int } @RunWith(MockitoJUnitRunner::class) class TestClass { @Mock private val fooMock: Foo = mock() private var temp = 0 @Before fun setup() { whenever(fooMock.property).then { invocation -> if (invocation.arguments.isEmpty()) { // this part works f

Unit testing Jest Enzyme Warning of ReactTestUtils location

I am using Jest with Enzyme (the former for a while, just starting with the latter). The relevant versions from my package.json: "devDependencies": { "enzyme": "^2.8.2", "jest": "^19.0.2", "react-addons-test-utils": "^15.5.1", "react-dom": "^15.4.2", "react-test-context-provider": "^2.1.2", "react-test-renderer": "^15.4.2" }, And a simplified version of the test I'm trying to run: import React from 'react'; import { shallow, mount, render } from 'enzyme'; import Dashboard from

Unit testing TFS - order of automata tests to execute

Supposing I have system tests: A and B, where A includes a record to a database, B tries to modify it. When A fails, B will fail as well. A and B are written as "unit tests" (test methods), A and B are tests cases in TFS as well, automated, linked to these "unit tests". I put them on a test plan, test suite, both of them. I want to execute them with the "Run Functional Tests" step. How can I tell TFS to execute them in the right order? What is the best practice to develop tests like these?

Unit testing How to write single test runner for classes with different @RunWith()?

I wrote simple method that executes tests in my test classes: DataContainerTest.class, AnotherTest.class. public static void main(String [] args) throws Exception { Result result = JUnitCore.runClasses(DataContainerTest.class, AnotherTest.class); System.out.println(result.getRunCount()); System.out.println("Total number of tests " + result.getRunCount()); System.out.println("Total number of tests failed: " + result.getFailureCount()); for(Failure failu

Unit testing KafkaTestUtils.getRecords() returns only first sent record

Sending 4 records: producer.send(new ProducerRecord<>("my-topic", 0, "key1", "value1")); producer.send(new ProducerRecord<>("my-topic", 0, "key2", "value2")); producer.send(new ProducerRecord<>("my-topic", 0, "key3", "value3")); producer.send(new ProducerRecord<>("my-topic", 0, "key4", "value4")); Using KafkaTestUtils.getRecords() get only first sent record; final ConsumerRecords<String, OrderBookViewItem> records = KafkaTestUtils.getRecords(consumer, 10000);

Unit testing junit test for for Login page using Mokito

// I need the junit test for login page i am new to testing.. // Additional information. // in the code dataBaseRepo is a interface reference //for private DataBaseRepo dataBaseRepo; //and database is reference for class DataBaseImplementaion dataBase = new DataBaseImplementaion();

Unit testing coverageThreshold for Jest with Lerna and yarn workspace not working

I have a yarn workspace with Lerna for a React project. Im using Jest. When I change the directory to packages/test-package-a, and then run yarn run test, which is "test": "jest" in the test-package-a package.json file, I see the code coverage report and the task fails because the coverage threshold is not met for unit test coverage. At the root of the project, not in the packages folder, I run yarn run test:all which runs: lerna run test, I see the code coverage report for

Unit testing Moq Verify Not Working as Expected After Upgrading to .NET Core 3.1

So as the title implies, this worked for us in .NET Core 2.2 and Moq Version 4.10.1. After upgrading to .NET Core 3.1 and Moq Version 4.14.5, the verify method is failing saying the method specified hasn't been called (no changes to the underlying code). I rolled back Moq to version 4.10.1 just to see if it was due to a change within the new version of Moq. I still get the same error. Trying to verify that a log message has been written to the ILogger. Weird thing is, if I debug the unit test

Unit testing How to unit test Spring Integration’s int-file:inbound-channel-adapter

I have a simple Spring Integration flow where I read XML files from a given directory, and send their content to another channel and do other processing. After the processing is done, I need to move the input file in an archive/error directory. file-integration.xml: <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int-file=&qu

Unit testing Do I have to refactor our codes in order to do google test(unit test)?

Basically when we developed, we didn't think about the unit test :(, so currently our codes structures are like: //MyClass to be tested #inculde "Dependency0.h" //Production Class #inculde "Dependency1.h" //Production Class ... MyClass { MyClass(){} void myClassMethods() { dependency0->func(); dependency1->func(); } Dependency0 *dependency0; //Production Class Dependency1 *dependency1; //Production Class } Based on my understa

  1    2   3   4   5   6  ... 下一页 最后一页 共 56 页