Posts

Showing posts with the label Unit Testing

AssertEquals Vs. AssertEqual In Python

Answer : Good question! Actually, in Python 2.6, both assertEqual and assertEquals are convenience aliases to failUnlessEqual . The source declares them thus: # Synonyms for assertion methods assertEqual = assertEquals = failUnlessEqual In Python 3, to your point, failUnlessEqual is explicitly deprecated. assertEquals carries this comment :-) # Synonyms for assertion methods # The plurals are undocumented. Keep them that way to discourage use. # Do not add more. Do not remove. # Going through a deprecation cycle on these would annoy many people. So, the upshot appears to be that you should use whatever you like for Python 2.x, but tend toward assertEqual for Python 3. A 3.3 update: From 26.3.7.1.1. Deprecated aliases : For historical reasons, some of the TestCase methods had one or more aliases that are now deprecated. The following table lists the correct names along with their deprecated aliases: Method Name | Deprecated alias | ...

"Cannot Drop Database Because It Is Currently In Use". How To Fix?

Answer : The problem is that your application probably still holds some connection to the database (or another application holds connection as well). Database cannot be deleted where there is any other opened connection. The first problem can be probably solved by turning connection pooling off (add Pooling=false to your connection string) or clear the pool before you delete the database (by calling SqlConnection.ClearAllPools() ). Both problems can be solved by forcing database to delete but for that you need custom database initializer where you switch the database to single user mode and after that delete it. Here is some example how to achieve that. I was going crazy with this! I have an open database connection inside SQL Server Management Studio (SSMS) and a table query open to see the result of some unit tests. When re-running the tests inside Visual Studio I want it to drop the database always EVEN IF the connection is open in SSMS. Here's the definitive way to ...

Android InstrumentationTestCase GetFilesDir() Returns Null

Answer : I think that you are right with keeping your test data separate from tested application. You can fix problem with Null by creating files directory for Instrumentation app by executing the following commands adb shell cd /data/data/<package_id_of_instrumentation_app> mkdir files You can do above only on emulator or rooted device. Then test from your question will not fail. I did it and also uploaded file named tst.txt to files dir, all below tests were successful: assertNotNull(getInstrumentation().getContext().getFilesDir()); assertNotNull(getInstrumentation().getContext().openFileInput("tst.txt")); assertNotNull(getInstrumentation().getContext().openFileOutput("out.txt", Context.MODE_PRIVATE)); But I think more convenient way to provide data to test project is to use assets of test project where you can simply save some files and open them: assertNotNull(getInstrumentation().getContext().getAssets().open("asset.txt"))...

Angular Unit Test Input Value

Answer : Inputs don't have textContent, only a value. So expect(field.textContent).toBe('someValue'); is useless. That's probably what's failing. The second expectation should pass though. Here's a complete test. @Component({ template: `<input type="text" [(ngModel)]="user.username"/>` }) class TestComponent { user = { username: 'peeskillet' }; } describe('component: TestComponent', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule], declarations: [ TestComponent ] }); }); it('should be ok', async(() => { let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.whenStable().then(() => { let input = fixture.debugElement.query(By.css('input')); let el = input.nativeElement; expect(el.value).toBe('peeskillet'); el.value = 'someValue'; el.d...

Cleanup After All Junit Tests

Answer : I'm using JUnit 4.9. Will this help?: import junit.framework.TestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({First.class,Second.class,Third.class}) public class RunTestSuite extends TestCase { @BeforeClass public static void doYourOneTimeSetup() { ... } @AfterClass public static void doYourOneTimeTeardown() { ... } } Edit: I am quite positive (unless I misunderstand your question) that my solution is what you are looking for. i.e. one teardown method after all your tests have ran. No listener required, JUnit has this facility. Thanks. I recommend to use org.junit.runner.notification.RunListener, example: public class TestListener extends RunListener { @Override public void testRunStarted(Description description) throws Exception { // Called be...

Angular Unit Test Error: No Component Factory Found For Component. Did You Add It To @NgModule.entryComponents

Answer : Testing is doubting. More seriously, let me answer you. In Angular, your components are handled by a module. When you use Material dialogs and snackers, you actually use a feature of the CDK, which is called Portal . This allow you to create your components dynamically. But when you do so, you have to add them to the entryComponents of your module. You did it in your module, so you should also do it in your tests. The syntax is TestBed .configureTestingModule(...) .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [YourComponent] } }); there are two places at which this is supposed to be done....entry components and also at declarations(while configuring your testing module).... TestBed .configureTestingModule({ declarations: [YourComponent], }) .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [YourComponent] } }); If someone struggling to find BrowserDynamicTestingModule just use BrowserModule ...

Can Google Mock A Method With A Smart Pointer Return Type?

Answer : A feasible workaround for google mock framework's problems with non (const) copyable function arguments and retun values is to use proxy mock methods. Suppose you have the following interface definition (if it's good style to use std::unique_ptr in this way seems to be more or less a philosophical question, I personally like it to enforce transfer of ownership): class IFooInterface { public: virtual void nonCopyableParam(std::unique_ptr<IMyObjectThing> uPtr) = 0; virtual std::unique_ptr<IMyObjectThing> nonCopyableReturn() = 0; virtual ~IFooInterface() {} }; The appropriate mock class could be defined like this: class FooInterfaceMock : public IFooInterface { public: FooInterfaceMock() {} virtual ~FooInterfaceMock() {} virtual void nonCopyableParam(std::unique_ptr<IMyObjectThing> uPtr) { nonCopyableParamProxy(uPtr.get()); } virtual std::unique_ptr<IMyObjectThing> nonCopyableReturn() { r...

A Way To Output Pyunit Test Name In Setup()

Answer : You can use self._testMethodName . This is inherited from the unittest.TestCase parent class. def setUp(): print "In method", self._testMethodName self.id().split('.')[-1] You can find the Documentation at: http://docs.python.org/library/unittest.html#unittest.TestCase.id edit: For 2.7 users, https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.id You can use str(self.id()).split()[4] . It could be found here http://docs.python.org/library/unittest.html#unittest.TestCase.id

Assert A Function/method Was Not Called Using Mock

Answer : This should work for your case; assert not my_var.called, 'method should not have been called' Sample; >>> mock=Mock() >>> mock.a() <Mock name='mock.a()' id='4349129872'> >>> assert not mock.b.called, 'b was called and should not have been' >>> assert not mock.a.called, 'a was called and should not have been' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: a was called and should not have been Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method. Just upgrade yours; pip install mock --upgrade You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest , you can...

Check If A Property Was Set - Using Moq

Answer : I think VerifySet is the right approach. It would look something like this: //Arrange var mock = new Mock<IDRepository>(); var mockRequest = new Mock<Request>(); // TODO: set some expectations here var dManager = new DManager(mock.Object); //Act dManager.Create(mockRequest.Object); //Assert mockRequest.VerifySet(x => x.Status = Status.Submitted); I believe in your case, it blows up because you haven't set up your Request mock to handle the set operation on Status. One easy way to do that is using SetupAllProperties , like so: //Arrange var mock = new Mock<IDRepository>(); var mockRequest = new Mock<Request>(); mockRequest.SetupAllProperties(); I think you should use strict behavior by default, then you can make the verification with a single call. It also makes you write your test more explicitly. [TestMethod] public void AddingNewRequestSetsStatusToSubmitted() { //Arrange var mock = new Mock<IDRepository>(MockBehav...