SSDT Unit Test - How to mock GETDATE()?

Some of our procedures/triggers returns values basing on current date, i.e.: GETDATE(), GETUTCDATE()
In such case a unit test will produce different result every time it is executed.
I found an article that one embeds GETDATE() into user defined function, and then at test runtime alters the function to return hardcoded date instead of current date.
http://pmichaels.net/2014/06/22/mock-current-date-and-time-in-sql-server/
What I don't like in such approach is that I will be forced to use custom user functions to get current date, change a lot of existing stored procedures and finally it can have negative impact on performance.
Is there a good method to handle such cases?

Hi, are you trying to just capture the day, month and year; something like '24-Apr-2015'?  If so try this code: -
Declare
@DateStr nvarchar(11)
Declare
@MonthNum int
Declare
@TempStr nvarchar(2)
Set
@Tempstr =(Select
Cast
(DatePart(dd,GetDate())
As
VarChar(2)))
IF
len(@Tempstr)=1
BEGIN
Set @Tempstr
=(Select
'0'+@Tempstr)
END
Set
@DateStr=(Select
(@TempStr+'-'))
Set
@MonthNum=(Select
DatePart(mm,GetDate()))
If
@MonthNum=1
Begin
Set @DateStr=(Select
(@DateStr+'Jan-'))
End
If
@MonthNum=2
Begin
Set @DateStr=(Select
(@DateStr+'Feb-'))
End
If
@MonthNum=3
Begin
Set @DateStr=(Select
(@DateStr+'Mar-'))
End
If
@MonthNum=4
Begin
Set @DateStr=(Select
(@DateStr+'Apr-'))
End
--Repeat above for all months
Set
@DateStr=(Select
(@DateStr+Cast
(DatePart(yyyy,GetDate())
As
VarChar(4))))
Print
@DateStr
Please click "Mark As Answer" if my post helped. Tony C.

Similar Messages

  • Unit test, how to test a function which returns a PL/SQL table.

    I've got the following type definition:
    create or replace type method_tbl as table of varchar2(255);
    /I've got the following function
    function abc(p_param1 in varchar2) return method_tbl;When I create a unit test for this I am not able to specify what the table should contain on return of the function, all I can see is an empty table. Which is off course one of the unit tests. But I also want to test where the table that is returned contains a number of rows.
    Is there something that I'm missing?
    Typically the function is called like this:
    select * from table(abc('a'));Thanks,
    Ronald

    >
    When I create a unit test for this I am not able to specify what the table should contain on return of the function, all I can see is an empty table. Which is off course one of the unit tests. But I also want to test where the table that is returned contains a number of rows.
    Is there something that I'm missing?
    >
    You will have to create a collection that represents the result set and then compare that to the actual result set.
    Assuming tables A and B you would typically have to do
    1. SELECT * FROM A MINUS SELECT * FROM B -- what is in A that is NOT in B
    2. SELECT * FROM B MINUS SELECT * FROM A -- what is in B that is NOT in A
    You could combine those two queries into one with a UNION ALL but since the results are tables and the comparison is more complex it is common to write a function to determine the comparison result.
    Here is sample code that shows how to create an expected result collection.
    DECLARE
    expectedItemList sys.OdciVarchar2List;
    functionItemList sys.OdciVarchar2List;
    newItemList sys.OdciVarchar2List;
    expectedCount INTEGER;
    countFunctionItemList INTEGER;
    BEGIN
    expectedItemList := sys.OdciVarchar2List('car','apple','orange','banana','kiwi');
    expectedCount := 5; -- or query to count them
    functionItemList := sys.OdciVarchar2List('car','apple','orange','peanut');
    -- use your function to get the records
    -- select * from myFunctino BULK COLLECT INTO functionItemList
    IF functionItemList.count != expectedCount THEN
      DBMS_OUTPUT.PUT_LINE('Count is ' || functionItemList.count || ' but should be ' || expectedCount);
    END IF;
    END;
    Count is 4 but should be 5If the collections are the same type you can use the MULTISET operators.
    See Solomon's reply in this thread for how to use the MULTISET operators on collections.
    PLS-00306: wrong number or type of argument in call to 'MULTISET_UNION_ALL'
    See MultisetOperators in the SQL Reference doc
    http://docs.oracle.com/cd/B13789_01/server.101/b10759/operators006.htm
    >
    Multiset operators combine the results of two nested tables into a single nested table.

  • Unit Tester: how to refactor

    I' using SQLDeveloper Version 2.1.1.64 Build MAIN-64.45 (german locale).
    How can I edit an existing unit test in case the name of the function/procedure under test changed or it's arguments?
    The user guide at OTN schows a pecile icon which I dont have...
    bye
    TPD

    So the answer is: no way. :o(
    The way I currently refactor my Test is to export my test (suit) to an XML file and change names of procedures, functions and parameters in the XML file.
    If a new parameter is introduced I first create a new Test, export it to XML (along with the existing test) and copy the tags of the new parameter to the old tests XML file. (Down't forget to change implementation ID...)
    Hopefully SQLDeveloper gets some refactoring features for unit test soon...
    bye
    TPD

  • Unit Tester - How to Rollback After Test Runs?

    Nevermind - I figured out my problem.
    Edited by: user453545 on Jan 29, 2010 1:08 PM

    - just so the answer is here if someone else looks at the thread ...
    Common practice is to put the rollback in the tear down for the test.
    Brian Jeffries
    SQL Developer Team

  • Abap unit test debug

    when use unit test,how to start up debug model?

    You can put breakpoints in your unit test methods (or helper methods) the same way you can in regular ABAP. As long as it is being executed in the foreground it should be tripped. I have noticed some quirky behavior about when it allows me to place a breakpoint in the code and when it places the breakpoint on the report statement at the beginning of my program, but it IS possible. I do it frequently.
    Regards,
    Andy

  • How can I unit test my Swing application?

    Hi All,
    In my application I came across a situation where I have to automate the unit testing of my application.
    Using my application user can able to draw polylines and rectangles on a BufferedImage added to a JFrame.
    Can any one please help/suggest me, how to automate the drawing process (this process consists of drawing the polylines with mouse and few action/mouse events)?
    your help will be highly helpful to me.
    Satya

    What exactly will that unit test prove? That you can mock the drawing of lines?
    Unit test are supposed to test certain parts of your application code - I'd concentrate on unit tests that are actually useful and for example in the future can help to catch regressions.
    If anywhere you can get help creating unit tests of this magnitude, I'd look in the unit testing support for Swing applications. Google for "java swing unit test" to see what you can come up with. Probably you'll need to create some plumbing yourself to make custom painting unit-testable; perhaps you could do something with painting to a BufferedImage in stead of to a Swing component for example.

  • Flash Builder 4.6 - How can I keep unit test classes out of the finished swc?

         I have a library of code I'm building and I'm working on unit testing but I have a major issue. When my finished swc compiles no matter what I do it includes the unit test classes as part of the intellisense if you load the swc via flash. The classes aren't really in the swc since if you just try and import them they'll come up undefined. They only appear to go into the intellisense for the swc. Does anyone know how can I keep this from happening in the finished source? Currently my folder setup is like this in flash builder.
    src\main - source documents for the library to get compiled
    src\mock - mock class area for unit testing
    src\test - unit test classes
         In the project Properties panel > the first tab of my Flex Library Build path I have selected only the src\main folder for the classes to inlude in the library. No other folder paths are selected.
    The "Flex Library Build Path" doesn't change my results with any setting.
    Thanks,

    Mel Riffe,
    Here's a Help topic about compiler options in Flash Builder: http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb524b8220812e5611f28f-7fe7. html
    For information on using mxmlc, the application compiler, to compile SWF files from your ActionScript and MXML source files, you can see: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fcc.html
    Hope this helps,
    Mallika Yelandur
    Flash Builder Community Help & Learning
    Adobe Systems Incorporated

  • How can I compare the actual and expected values in Unit testing when they are XML files?

    I have created a unit test for a method in VS 2008. My expected value and actual value are XMLs. Therefore though the output is same as I expect it gives an error as I am doing string comparison now. How can I compare these 2 XMLs in expected output and
    actual output format in Unit Testing?
    mayooran99

    In unit test, when you want to validate XML files, you feed them into the class / struct that you want to feed the XML into and compare the values there (You don't just feed it in XMLReader and feed it line by line, right? But if it really is, that's how
    you should also test it in unit tests).
    In short, how you'd use the XML in your code, that's how you should test it in unit test.

  • I can't figure out how to set a breakpoint in a SenTestingKit unit test

    I'm learning Cocoa after decades of doing other languages. I'm trying to use SenTestingKit for unit tests. One of my unit tests doesn't work, and I want to set a breakpoint to figure out why. So far, I haven't figured out how to do this.
    I found Chris Hanson's instructions for how to do this, but he apparently wrote them for an earlier version of Xcode, and I don't know enough to adapt them.
    I am writing a tutorial document for writing a simple Cocoa App using Xcode 3.1, git, SenTestingKit, and OCMock. It's at http://xorandor.com/FirstCocoaApp. I've got it up to the point of trying to debug a unit test, and I'm stuck there.
    I also couldn't figure out how to have Xcode run the unit tests while building the application. Again, Chris' instructions didn't quite do it, and I don't know enough to figure out the rest.
    So, if you know how to do this, please give me some hints. I'll put those into my tutorial, so that the next people who need this can find it.
    Thanks,
    Pat

    I figured out more of my problem, but I haven't solved it yet.
    What happens is that, after I create a test case, I try to run it with a breakpoint. After I start the program, Xcode turns the breakpoint from blue (meaning active) to orange (meaning that it can't set the breakpoint).
    Several people have said to turn off the Lazy symbol loading preference. I did that, and that didn't fix the problem.
    I wrote up a detailed list of steps that I took at http://www.xorandor.com/DebugQuestion.txt
    I also put a copy of the project file at http://xorandor.com/MyProject.tar
    If anyone has any suggestions on what to try next, please let me know.
    Thanks,
    Pat

  • SSDT: Creation of localDB instances from project file - Sql Server Unit testing purposes

    I have a SqlServer Database Project in my solution (VS2013 Professional) which has a corresponding test project with some stored procedure unit tests. Currently I am using a LocalDB and as far as I understand a local database instance is created in C:\Users\[User]\AppData\Local\Microsoft\Microsoft
    SQL Server Local DB\Instances\Projects and the specific .mdf file referenced in the SQL Server Object Explorer is in C:\Users\[User]\AppData\Local\Microsoft\VisualStudio\SSDT\[ProjectName]. The unit tests run fine on my local machine which I have developed
    the project on.
    My issue is we have a box which is configured to check out the project file from our version control, build the project using ms build commands and then run the unit tests using VSTest.Console. Usually with C# Test projects we reference the test project
    dll and the unit tests run fine. I have referenced the dll for the test project with the stored procedure unit tests in. 
    With the Stored Procedure unit tests however we get this exception: 
    Initialization method [project].[spTest].TestInitialize threw exception. System.Data.SqlClient.SqlException: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.
    After some digging I have realised that the localdb instance seems to be created when the project itself is created in VS not when it is built. Specifically when the localdb is first used and if you look into the appData folder of the test machine there
    is no corresponding mdf file for the project.  
    The question is is there a way to set up a localDB instance on the new machine if all you have the project file? The only purpose of the project on the test machine is to run the unit tests, no other development purposes. VS2013 Professional is installed
    on the test machine but a solution only using config file changes or MSBuild/VSTest commands would be preferable.
    I realise you could change the connection string to an actual test database and run the unit tests of that but we quite like the localdb approach for the testing. I also realise that you could potentially transfer the mdf file (haven't tested this solution)
    as well, though I would prefer if there is a solution to my initial question. 
    http://technet.microsoft.com/en-us/library/hh234692.aspx
    http://msdn.microsoft.com/en-us/library/hh309441(v=vs.110).aspx
    I have been reading up on LocalDB and I assume a automatic LocalDB is created when you create a sql server database project (ie on localdb first use). I have tried adding the database creation to the test project config file but do not really know where
    to go from there. The second link does not really specify when the named localdb will be created if you add the config items and I am not even sure if that is an actual solution.  Here's my test project config file for reference
    <configSections>
    <section name="system.data.localdb" type="System.Data.LocalDBConfigurationSection,System.Data,Version=4.0.0.0,Culture=neutral,PublicKeyToken=[PublicKeyToken]"/>
    <section name="SqlUnitTesting_VS2013" type="Microsoft.Data.Tools.Schema.Sql.UnitTesting.Configuration.SqlUnitTestingSection, Microsoft.Data.Tools.Schema.Sql.UnitTesting, Version=12.0.0.0, Culture=neutral, PublicKeyToken=[PublicKeyToken]" />
    </configSections>
    <system.data.localdb>
    <localdbinstances>
    <add name="SimpleUnitTestingDB" version="11.0" />
    </localdbinstances>
    </system.data.localdb>
    <SqlUnitTesting_VS2013>
    <DatabaseDeployment DatabaseProjectFileName="..\..\..\SimpleUnitTestDB\SimpleUnitTestDB.sqlproj"
    Configuration="Release" />
    <DataGeneration ClearDatabase="true" />
    <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\Projects;Initial Catalog=SimpleUnitTestDB;Integrated Security=True;Pooling=False;Connect Timeout=30"
    CommandTimeout="30" />
    <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\Projects;Initial Catalog=SimpleUnitTestDB;Integrated Security=True;Pooling=False;Connect Timeout=30"
    CommandTimeout="30" />
    </SqlUnitTesting_VS2013>
    Thanks in advance for any response. Sorry if there is any misunderstanding, while I have been using VS to develop from the start, this is the first time I have used a Sql Server Database Project. 
    Regards,
    Christopher. 

    Yes, you can create a LocalDB instance manually. You use the SqlLocalDb utility, see here:
    http://technet.microsoft.com/en-us/library/hh212961.aspx
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to debug in dedicated unit test client

    Hello,
    We have a setup where we do all development in client 100, but have a separate client for unit tests. Since this is the client holding relevant test data, we would like to debug in this client.
    How can I achieve this in Eclipse, do I need to create two projects (one for each client) and open the object twice, or is it possible to setup using debug configurations or something similar?
    Regards

    Hi Matthias,
    in Java you need OS privileges to debug Java code running on any Java application server (and additionally set up the Java VM in debug mode and stuff like that). And once you have OS privileges, you can of course debug all Java VM processes/threads on the machine, regardless which application context they are currently running for.
    In ABAP you do NOT need any kind of OS privileges in order to debug. All you need is a user in the system/client with debug privileges, which is big advantage in terms of privilege separation. ABAP debugging on customer systems for example, which is a quite normal thing, would be much harder to realize, if we require any kind of OS privileges.
    To cut a long story short:
    As a user is required with debugging privileges in any ABAP system/client for ABAP debugging, it is not possible to realize a remote debugging in ABAPinEclipse just by specifying SID/client of the remote ABAP system.
    So you need to logon to the ABAP system/client (and set breakpoints there) in order to debug. And as the system/client logon to the ABAP backend in ABAPinEclipse is conceptually linked to a project, you need to have an open project for those ABAP system/clients you want to debug in.
    Regards,
    Christoph Stoeck, ABAP Language

  • How do you debug your unit tests?

    Hey folks,
    I'm obviously doing something wrong that I can't figure out. I've tried following Chris Hanson's instructions that he put on LJ. No matter what I do, I can't get the debugger to breakpoint in a unit test, no matter whether I put the breakpoint in the test code or the worker code. I can get it to breakpoint just fine in the worker code when I run the real app.
    How do you do this on your unit test code?
    Thanks,
    Pat

    Tried that. No joy so far. That's why I asked here; I hoped that someone here had done it successfully.
    Pat

  • How to make a Abap Unit Test Suit with many test classes

    Hi,
    Problem space
    we have different packages(embedded) in our project and each package corresponds to a differnt functional layer in the design.
    We want to create abab unit test classes for these different layers.
    say embedded package 1 has 10 unit test classses
          embedded package 1 has 20 unit test classses
    How to grup these classes together so that we can start them frm a test suite.
    Code examples and blogs links will be appreciated.
    regards
    anubhav

    This sounds a bit like Project Administration 101 to me.
    I'm not exactly sure what you are actually trying to do here --but generally if you want to functionally test something you need to start with a business process -
    You need to create scripts which tell the user the data to be entered, the transaction to be used and the outcome.
    With SAP you might need to show screen shots of each stage as well.
    You follow this for each complete business process until you've covered the whole business cycle.
    You complete this say individually for Logistics, Purchasing and Finance and then compare what SAP gives you with what you expected to get.
    For some type of testing CATTS can help but without the business processes any testing is essentially meaningless.
    It is totally pointless trying to design a "generic" test plan until you've got the functional consultants to describe the business processes involved.
    Cheers
    jimbo

  • What is utp and who will do this ?how you do unit testing?

    Hi....
    he asked me like this
    1...what is utp and who will do this ?how you do unit testing?
    thanks and regards,
    k.swaminath reddy.

    Hi Swaminath,
    Adding to what Sandhya told..When the huge work is diveded by units, each unit is assigned to a Developer.After complition of the assigned work Developer has to do testing that object by seeing that Unit Plan or Creating Unit Plan.
    Regards,
    Ameer Baba.

  • How  to genearte Unit Test reports  through  ANT/Command  line ?

    Hi,
    I am using sql developer unit test feature to test my database code. I am planning to execute and generate reports by running ant script.
    Is it possible to get the unit test results in any format (text,XML,HTML) after running the tests.
    How to integrate report generation tasks as part of Automated builds?
    Is there any command line utility do through can invoke through ant task?
    Thanks,
    Fernando

    Fernando,
    I, too, am looking to run our PL/SQL unit test suites through our automated ant build scripts. Currently, I've only been able to determine that there is a "UtUtil.bat" and "UtUtil.sh" command line utility for win and linux in /sqldeveloper/sqldeveloper/bin. However, it only take three switches:
    UtUtil -run ?
    UtUtil -imp ?
    and
    UtUtil -exp ?
    While this does provide some limited value to us through automating the importing of our exported test suites and then running them as part of our builds, it doesn't help in running reports on the test runs and exporting the reports to something our build processes can consume (i.e. xml).
    Also, we want to be able to run our full db build on (almost) any of our development machines and we don't want to have to have a unit test repository already preconfigured on each development db. I haven't found a utility to automate the creation of the unit test repository user and the repository, and then whena all the test suite runs have finished and the reports run, delete the repository and repository user.
    We have used Quest's Code Tester product in the past and it had all of these great features that I am really hoping Oracle can either implement or expose to us.
    Regards and best of luck,
    Mike Sanchez

Maybe you are looking for

  • Creating dynamic HTML form from XML data in session

    I'm a bit new to servlets, please bear with me if I don't make myself clear. currently i have a HttpServlet that extracts a XML document into a jdom Document. this is done within the doGet() method as the XML document is in the session object. i woul

  • CM issue

    we have a vision server on windows. The issue is with CM. i can start them from component services.However all the requests shows "Inactive manager" Only the Internal manager shows 1,1 as actual and target while other managers are not running.They sh

  • Time Capsule - Overheating

    I received an alert from my Time Capsule that it was overheating. I immediately put a fan on it and it seemed to cool down rather quickly. My TC is placed on a desk with no obstructions of airflow... As any one else experienced this? When I received

  • Accessing XI web service from portal as client

    Hi all I need to access a web service which has been created on XI     server. I want to acess it from enterprise portal as a web service client. please provide related links to achieve this. thanks in advance vaishali

  • Export Data Base

    Hi, I am taking Data base backup using Batch file and that file assign to Schedule.so every day automatically it is executing and saving to file. That batch file contains below script. exp pplus/computer@abcd file=e:\bkup\pplus.dmp grants=Y buffer=10