Questions tagged [unit-testing]

33996 questions
1

votes
1

answer
100

Views

How to test a method that makes calls to a database

I have several methods that make connections to a database and I can't figure out how to write unit tests for them. Here is a sample of what I'm talking about. public static User GetByPendingUserId(int a_PendingUserId) { User l_User = new User(); SqlConnection l_conn = DbHelp.CreateSqlConnection();...
tayopi
1

votes
2

answer
2.7k

Views

How to Mock System.getProperty using Mockito

I have added mock-maker-inline text in org.mockito.plugins.MockMaker file and placed it in test/resources/mockito-extensions In my test case I am using: System system = mock(System.class); when(system.getProperty('flag')).thenReturn('true');` But I am getting the following exception: org.mockito.ex...
Raghu
1

votes
1

answer
386

Views

Java JUnit 5 annotations differences

I see there was introduced the new JUnit Jupiter according to JUnit 5 User Guide. JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage I am confused about the same-named annotations I use across the library. Is there any significant difference between these two ones? org.junit.Test org.junit.jup...
Nikolas
1

votes
2

answer
654

Views

Override Go Method in Tests

So I have this Client struct that has a method UserByID that makes a HTTP request to an endpoint for a User. I want to unit test this function but also not make an actual HTTP request in the function c.Request. I want to stub that function with a response and error I can control. func (c Client) Use...
KA01
1

votes
1

answer
861

Views

Mocking Vuex module action in component unit test

I'm currently trying to mock an action from a store's module. I can't seem to properly stub it, as I continue to get a message in my unit tests that says: [vuex] unknown action type: moduleA/filterData Here is a simplified version of the component under test: Item.vue {{ itemName }} import store fro...
imcz
1

votes
2

answer
428

Views

Symfony 4 Mock service in functional test

I am testing a service which essentially is mostly serializing an object and sending it via a service to an external system. If I create the typical unittest I would mock the response of the serializer and of the service, which contacts the external system. In fact there would be not much left to te...
Calamity Jane
1

votes
1

answer
613

Views

Code coverage analysis using CodeCoverage.cmake with multiple targets

I have unit-test in my project implemented using Boost Unit Test Framework and organized into several modules, i.e.: #define BOOST_TEST_MODULE Connection_test #ifndef BOOST_TEST_DYN_LINK #define BOOST_TEST_DYN_LINK #endif #ifndef BOOST_TEST_NO_MAIN #define BOOST_TEST_NO_MAIN #endif #include #includ...
Eenoku
1

votes
2

answer
683

Views

Angular 5 Unit testing throwing error for “components should create ” test case

I am trying Angular 5 unit testing for the first time. While I already created the app then decided to run testing in it. But I am getting these errors: AppComponent should create the app AppComponent should have as title 'app' AppComponent should render title in a h1 tag GalleryComponent should cr...
vietngogs
1

votes
3

answer
245

Views

In Unity3d test scripts, how do I call a static function from another class?

I have two files in a Unity3d project. One is a test script that runs in edit mode. The other is a single class with static functions that I'd like to call from the test scripts. here's my test script: using UnityEngine; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections;...
Brad
1

votes
2

answer
144

Views

Testing Rx Java interval

I have a repeated observable inside a ViewModel as below: class MainViewModel @Inject constructor(private val ratesUseCase: RatesUseCase) : ViewModel() { private var disposable: Disposable? = null private val resultLiveData = MutableLiveData() fun result() = resultLiveData fun getRates(base: String)...
Jamal
1

votes
1

answer
48

Views

AndroidThreeTen not working in unit test without robolectric?

I'm having trouble creating a unit test without needing robolectric. I am using AndroidThreeTen.init(this) in my code and when I run my test if I disable robolectric I get an error: org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered and if I leave it enabled I get this: [Ro...
Crash1hd
1

votes
2

answer
37

Views

how to use builtins.input for multiple inputs

In my unittest, I have 2 prompts in the test. I am trying to use 2 @patch('builtins.input'), but it seems to only take the 1 of the return values. @patch('builtins.input') @patch('builtins.input') def test_setProfileName_modify_init_prompt_empty(self, paramName1, paramName2): paramName1.return_valu...
kiwo
0

votes
0

answer
9

Views

Karma, Angular 7, & FontAwesome issue Can't bind to 'icon' since it isn't a known property of 'fa-icon'

Can't bind to 'icon' since it isn't a known property of 'fa-icon'. When trying to run this test in people.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PeopleComponent } from './people.component'; describe('PeopleComponent Unit Test', () => { le...
John Peters
0

votes
1

answer
18

Views

Test calculations when there is no reference to check against

How to test (in pytest) calculations when there is no reference to check against? Say, I have a dataframe with a and b columns. And column c is calculated using a and b. The results are float numbers. df = pd.DataFrame({'a': [4,3,5], 'b': [11,7,13]}) df['c'] = df['a']/df['b']
anarz
1

votes
0

answer
4

Views

Testing a utility function by writing a unit test in apache spark scala

I have a utility function written in scala to read parquet files from s3 bucket. Could someone help me in writing unit test cases for this Below is the function which needs to be tested. // function to get parquet dataset from s3 def readParquetFile(spark: SparkSession, locationPath: String): DataFr...
wandermonk
1

votes
2

answer
216

Views

Unit Testing valid inputs to a method

The question is whether it is bad practice to have a method in your Application project that has no other purpose than to generate data for your test project. I have a unit test that I am using to do a cursory exam to ensure that all valid inputs will run through the primary method of my application...
TimidObserver
1

votes
2

answer
338

Views

Custom User Testing in Django

I have a Django application and the custom user - want to test it (do unit testing). My custom user is emailuser, which consists of e-mail and password fields. I want to set up something of such national mplayer, give it a field and a password. But my code below does not work. settings.py AUTH_USER_...
mark
1

votes
1

answer
383

Views

MVC 5 Unit tests vs integration tests

I'm currently working a MVC 5 project using Entity Framework 5 (I may switch to 6 soon). I use database first and MySQL with an existing database (with about 40 tables). This project started as a “proof of concept” and now my company decided to go with the software I'm developing. I am strugglin...
Pierre
1

votes
1

answer
686

Views

pytest: If a crash/segfault/etc. occurs during testing, is there a way to make pytest log the crash as a test failure and continue testing?

I have a few unit tests written using pytest that have successfully caused segfaults to occur. However if a segfault occurs (on my Mac) during these execution, pytest seems to quit altogether and provide no information on what caused the python interpreter to crash. Now I could infer from the logs t...
nonbot
0

votes
0

answer
11

Views

Is there any good reason to catch exceptions in unittest transactions?

The unittest module is extremely good to detect problems in code. I understand the idea of isolating and testing parts of code with assertions: self.assertEqual(web_page_view.func, web_page_url) But besides these assertions you also might have some logic before it, in the same test method, that coul...
1

votes
2

answer
3k

Views

Android. @RunWith(AndroidJUnit4.class) - cannot resolve in package “androidTest”

Android Studion 2.2.3 Install Android Support Repository - ver. 44.0.0 I setup all as in official site for Espresso: https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html I try to write instrumentation test (Espresso) in package androidTest. So I create StringUtilAn...
Alexei
1

votes
2

answer
1.4k

Views

How to perform assertion on all remaining elements in StepVerifier?

StepVerifier has an assertNext method that allows performing an assertion on a value of next element. StepVerifier.create(dataFlux) .assertNext(v -> checkValue(v) .verifyComplete(); What is a good way to perform assertion for every remaining element (e.g. to check that every element is positive)? I'...
Dmitriusan
1

votes
1

answer
824

Views

Angular unit test error: Unexpected value 'ObservableMedia' imported by the module 'DynamicTestModule'

I have a fairly simple unit test file like so: import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Http, HttpModule } from '@angular/http'; import { MockBackend } from '@angular/http/testing'; import { MaterialMod...
isherwood
1

votes
2

answer
1.4k

Views

Angular2 Unit test for Observable.interval

I have a service that polls data from server every 500 milliseconds. For this i have used Observable.interval(). Below is my code. I want to write the unit test for this service service.ts: pollData() { Observable.interval(500).mergeMap(() => this._http .get(url, { headers: headers }) .map((resp: Re...
user1722632
1

votes
0

answer
16

Views

AngularJS unit testing Karma - unknown provider

I am trying to set up unit tests on our legacy AngularJS app. I am using the standard karma along with angular-mock to set up the tests cases. But I am getting issues with Unknown provider when I am trying to inject some services and factory. My karma.conf looks something like this (I have removed a...
Tushar Chutani
1

votes
2

answer
1.3k

Views

How can I resolve Angular unit test error: “An error was thrown in afterAll\n[object ErrorEvent] thrown”

When I run ng test command in my angular project has error, it gives an error like that 10% building modules 1/1 modules 0 active04 12 2018 11:29:43.408:WARN [karma]: No captured browser, open http://localhost:9876/ 04 12 2018 11:29:43.414:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:...
Samet ÇELİKBIÇAK
1

votes
1

answer
52

Views

JEST: select an HTML element through innerHTML

Folks, I have a React Component which on rendering has this HTML in it: 1 It's a pagination button, and I want to simulate a click on it. The hacky way to select this element was: const wrapper = Enzyme.mount(); wrapper.find('button.encryped-class__2TKgPzyme4') .first() .simulate('click'); I want to...
darth-coder
1

votes
1

answer
1.2k

Views

How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

.NET Core 2.1 comes with this new factory called HTTPClientFactory, but I can't figure out how to mock it to unit test some methods that include REST service calls. The factory is being injected using .NET Core IoC container, and what the method does is create a new client from the factory: var clie...
Mauricio Atanache
1

votes
1

answer
76

Views

How can I unit test an Asynchronous method in F#?

I've got a method that returns a task I'm trying to test synchonously in F#. Here's the method, which is an implementation of a C# interface: member this.RunAsync(): System.Threading.Tasks.Task = async{ this._settings.LogSettings |> Seq.iter(fun settings -> this.clearLogs(settings)) |>...
reckface
1

votes
1

answer
30

Views

Using Moq to test call to different class

The problem I have the following method: public void ParseRebootData(RebootDeviceDto rebootDeviceDto) { if (rebootDeviceDto.RebootAtUtc.CompareTo(DateTime.UtcNow)
Devator
1

votes
2

answer
71

Views

How to unit test a UIButton that calls an asynchronous task

I am trying to test a login method triggered by a IBAction that if the login failed (if the completion hander returned a error), I want to present an alert controller, but the login method is obviously an asynchronous. The loginUser method is already mocked and always returns handler(nil, .EmptyData...
Brendon Cheung
1

votes
2

answer
47

Views

MSTest ThrowsException with conditions on the exception object?

I'm using MSTest Assert.ThrowsException, but sometimes I want to add test conditions on the thrown exception object, e.g. checking that the message mentions a specific phrase, identifier, data value or whatever. The best solution I've found is a construct that doesn't use Assert.ThrowsException, but...
Kjell Rilbe
1

votes
3

answer
52

Views

How can I test if a private method of a class is called or not with rhino mock?

I am quite new at C# and also rhino mocks. I searched and found similar topics with my question but couldnt find a proper solution. I am trying to understand if the private method is called or not in my unit test. I am using rhino mock, read many files about it, some of them just say that change t...
SSanc
1

votes
3

answer
45

Views

Relationship between Unit Testing & End-to-End (Integration per se) while following BDD

My question is also related to who does what in typical BDD. My understanding, Product owner comes up with User Story (may or may not in Gherkin), QA writes Scenarios for End-to-End testing(in feature files), Dev writes his code (how and where, does he follow BDD as well?). At this point if the Dev...
Anup
1

votes
1

answer
45

Views

How can I mock a simple method using Moq framework?

Let's say I've a simple method which checks whether the passed number is Even & returns a boolean value. I'm new to mocking & trying it out. How can I mock this method using Moq framework? public bool isEven(int x) { bool result = (x % 2 == 0) ? true : false; return result; }
Tim Smith
1

votes
1

answer
63

Views

How to unit test return value of function - Angular (Jasmine/Karma)

I am wondering if there is a way to correctly test the return value of a function in Angular. I want to essential test the return value to be true for one test and write another to test the opposite scenario. Ts component: get() { if (this.object == undefined) { return true; } else { return false;...
thenolin
4

votes
1

answer
163

Views

Jest - How to get coverage for mocked classes and implementations

I'm currently working on a project where I'm using Jest for unit testing and code coverage. Everything is working fine, except coverage for mocked classes/methods. I don't seem to get the desired coverage results. I've tried to find something in the Jest docs and searched online for an answer, but I...
0

votes
0

answer
6

Views

Trying to convert this Mockito test to Mockk results in error

Having issues with the following conversion from Mockito to Mockk. So I have this @Mock private lateinit var loginLiveDataObserver: Observer val inOrder = inOrder(loginLiveDataObserver) inOrder.verify(loginLiveDataObserver).onChanged(enableLoading) inOrder.verify(loginLiveDataObserver).onChanged(log...
Crash1hd
1

votes
2

answer
59

Views

How to mock Spark DataFrameReader using scala?

I want to unit test code that read DataFrame from RDBMS using sparkSession.read.jdbc(...). But I did't find a way how to mock DataFrameReader to return dummy DataFrame for test. Code example: object ConfigurationLoader { def readTable(tableName: String)(implicit spark: SparkSession): DataFrame = { s...
dytyniak
1

votes
1

answer
39

Views

Not success trying to test my catch block inside of then

I'm new on the unit testing code and lost! I'm trying throws an error for the following function to cover the catch block, but not having success and I don't know why. Function: public initialize(): Promise { return Promise.resolve() .then(() => this.getQueries()) .catch((error: Error) => { this.con...
Andre Moraes

View additional questions