From the TestNG doc I can see that (enabled = false) can be applied to a class or method. But it seems it only works when applied to a method.
Anybody seen the same, found a solution?
It seems to work for me:
#Test(enabled = false)
public class B {
public void btest1() {
System.out.println("B.btest1");
}
}
Result:
===============================================
SingleSuite
Total tests run: 0, Failures: 0, Skips: 0
===============================================
Changing false to true:
B.btest1
===============================================
SingleSuite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
Possible reason
Here is what might be tripping you (hard to tell since you didn't provide any code):
#Test(enabled = false)
public class B {
#Test
public void btest1() {
System.out.println("B.btest1");
}
}
This case will run the test because by repeating the #Test annotation on the method, you are also overriding the enabled attribute to its default value, which is true.
The solution is to reiterate enabled=false at the method level:
#Test(enabled = false)
public class B {
#Test(enabled = false)
public void btest1() {
System.out.println("B.btest1");
}
}
I'm aware it's a bit counterintuitive but it's necessary in order to be consistent in the way method annotations can override class annotations.
Related
I'm new to Dependency Injection and I have been doing my research for a few days now but can't seem to find answers; there is not a whole lot of examples out there specific to zenject so I have been looking into both specific zenject solutions as well as DI in general.
Using Unity 2018.3f and Zenject 7.3.1.
I'm using an interface IModifiableService in order to constructor inject my ModifiableService class into my ModifiableField class in order to fill it's dependency.
During the console log in the constructor it is logging out "ModifiableService" as expected. When used again in a separate method which is called from the ModifiableField script to trigger Calculate() the console log is null. I seem to be missing something or doing this incorrectly so I would greatly appreciate any resources or advice in order to better understand DI and how to fix my issue. Thanks!
public class ModifiableField
{
[SerializeField] private ModifiableProperty propertyToModify;
[SerializeField] private float modificationAmount;
[SerializeField] private IModifiableService _modifiableService;
ModifiableField(IModifiableService modifiableService)
{
_modifiableService = modifiableService;
//Not Null
Debug.Log(_modifiableService);
}
public IModifiableService ModifiableService { get => _modifiableService; private set => _modifiableService = value; }
public ModifiableProperty PropertyToModify { get => propertyToModify; private set => propertyToModify = value; }
public float ModificationAmount { get => modificationAmount; private set => modificationAmount = value; }
public void Calculate()
{
//Null
Debug.Log(_modifiableService);
ModifiableService.TriggerAttributeChange(PropertyToModify);
}
}
Binding:
public class MISInstaller : MonoInstaller
{
public override void InstallBindings()
{
SignalBusInstaller.Install(Container);
//Both of these lines to bind IModifiableService produce the same null result.
//Container.BindInterfacesAndSelfTo<ModifiableService>().AsCached().NonLazy();
//Container.Bind<IModifiableService>().To<ModifiableService>().AsCached().NonLazy();
Container.Bind<ModifiableField>().AsTransient().NonLazy();
Container.DeclareSignal<ModAgilitySignal>();
Container.DeclareSignal<ModStrengthSignal>();
Container.BindInterfacesAndSelfTo<ModAgilitySignal>().AsCached().NonLazy();
Container.BindInterfacesAndSelfTo<ModStrengthSignal>().AsCached().NonLazy();
Container.BindSignal<ModAgilitySignal>().ToMethod(() => Debug.Log("Agility Modifiable Signal Fired."));
Container.BindSignal<ModStrengthSignal>().ToMethod(() => Debug.Log("Strength Modifiable Signal Fired."));
}
}
Tried changing it to do the same thing a different way in the installer; same result was achieved, making me think my installer is the problem and it was not being bound correctly in either of my above attempts.
Is there a way to run an identical set of tests over multiple objects, but toggle each test depending on the type of said objects?
i.e. if I had classes
abstract class MyObj{ abstract bool DoWork(bool isTrue); }
class SubObj1 : MyObj{ override bool DoWork(bool IsTrue){return IsTrue; } }
class SubObj2 : MyObj{ override bool DoWork(bool IsTrue){return false; } }
and tests
class Tests
{
[Test]
void Test1() { Assert.IsTrue(new SubObj1().DoWork(true)) }
[Test]
void Test2() { Assert.IsTrue(new SubObj1().DoWork(false)) }
}
I'd like to be able to use flags, type checking, or something so that I:
could replace the references to SubObj1 with a MyObj instance,
Run the class Tests over both SubObj1 and SubObj2, but prevent Test1 from running if working with a SubObj2 instance? EDIT: This part can be done with Assert.Ignore.
(The real case in my code involves three different unstructured-data parsers, each of which trade simplicity for accuracy in a different way. I have 400 test cases for one parser, and would like to port them to the other two. Creating three nearly identical sets of tests cases and pruning the tests that don't work in each class seems like a massive DRY failure.)
You can do it very easy with TestCaseSourceAttribute. Something like:
class Tests
{
static object[] TestCases = new object[]
{
new object[] { new SubObj1(), true }
new object[] { new SubObj2(), false}
};
[Test, TestCaseSource("TestCases")]
void Test1(MyObj obj, bool isTrue) { Assert.IsTrue(obj.DoWork(isTrue)) }
}
(I did not try to compile it, just shared the basic idea).
I have a method to be tested using TestNG and I have marked it with below annotations:
#Test(invocationCount=10, threadPoolSize=5)
Now, in my test method I would like to get the current invocationCount that is being executed. Is that possible? If yes, then I would be glad to know how.
More proper example:
#Test(invocationCount=10, threadPoolSize=5)
public void testMe() {
System.out.println("Executing count: "+INVOCATIONCOUNT); //INVOCATIONCOUNT is what I am looking for
}
For reference, I am using TestNG plugin in Eclipse.
You can use TestNG dependency injection feature by adding ITestContext parameter in your test method. Please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection.
From the ITestContext parameter, you can call its getAllTestMethods() which returns array of ITestNGMethod. It should returns array of only one element, which refers to the current/actual test method. Finally, you can call getCurrentInvocationCount() of ITestNGMethod.
Your test code should be more-less like the following sample,
#Test(invocationCount=10, threadPoolSize=5)
public void testMe(ITestContext testContext) {
int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
System.out.println("Executing count: " + currentCount);
}
You can get the current invocation count as mentioned below
public class getCurrentInvocationCount {
int count;
#BeforeClass
public void initialize() {
count = 0;
}
#Test(invocationCount = 10)
public void testMe() {
count++;
System.out.println("Current Invocation count "+count)
}
}
I know this is a some kind of stupid way. However it will server your purpose. You can refer testNG source class to get actual current invocationCount
You can use something like this:
public class getCurrentInvocationCount {
AtomicInteger i = new AtomicInteger(0);
#Test(invocationCount = 10, threadPoolSize=5)
public void testMe() {
int count= i.addAndGet(1);
System.out.println("Current Invocation count "+count)
}
}
You can get by calling getCurrentInvocationCount() method of ITestNGMethod
Try to put 2 parameters in #Test method:
java.lang.reflect.Method
Use .getName() to get current method name.
ITestContext
Use .getAllTestMethods() to get all test methods. Then use forEach to extract them by ITestNGMethod and compare with .getName() in point 1.
Finally, use .getCurrentInvocationCount() to achieve this.
#Test(invocationCount=10)
public void testMe(ITestContext context, Method method) {
int invCountNumber = 0;
for(ITestNGMethod iTestMethod: context.getAllTestMethods()) {
if(iTestMethod.getMethodName().equals(method.getName())){
invCountNumber = iTestMethod.getCurrentInvocationCount();
break;
}
}
System.out.println(invCountNumber);
}
Following import:
import java.lang.reflect.Method;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
When you use invocationCount the test is run like for loop.
I found this to be the easiest way to get the count of test executions.
int count;
#Test(invocationCount = 3)
public void yourTest() {
count++;
System.out.println("test executed count is: " + count)
}
I am having two Methods in Unit Test case where First Insert Records into Database and Second retrieves back data. I want that input parameter for retrieve data should be the id generated into first method.
private int savedrecordid =0;
private object[] SavedRecordId{ get { return new object[] { new object[] { savedrecordid } }; } }
[Test]
public void InsertInfo()
{
Info oInfo = new Info();
oInfo.Desc ="Some Description here !!!";
savedrecordid = InsertInfoToDb(oInfo);
}
[Test]
[TestCaseSource("SavedRecordId")]
public void GetInfo(int savedId)
{
Info oInfo = GetInfoFromDb(savedId);
}
I know each test case executed separately and separate instance we can't share variables across test methods.
Please let me know if there is way to share parameters across the test cases.
The situation you describe is one of unit tests' antipatterns: unit tests should be independent and should not depend on the sequence in which they run. You can find more at the xUnit Patterns web site:
Unit test should be implemented using Fresh Fixture
Anti pattern Shared Fixture
And both your unit tests have no asserts, so they can't prove whether they are passing or not.
Also they are depend on a database, i.e. external resource, and thus they are not unit but integration tests.
So my advice is to rewrite them:
Use mock object to decouple from database
InsertInfo should insert info and verify using the mock that an appropriate insert call with arguments has been performed
GetInfo should operate with a mock that returns a fake record and verify that it works fine
Example
Notes:
* I have to separate B/L from database operations…
* … and make some assumptions about your solution
// Repository incapsulates work with Database
public abstract class Repository<T>
where T : class
{
public abstract void Save(T entity);
public abstract IEnumerable<T> GetAll();
}
// Class under Test
public class SomeRule
{
private readonly Repository<Info> repository;
public SomeRule(Repository<Info> repository)
{
this.repository = repository;
}
public int InsertInfoToDb(Info oInfo)
{
repository.Save(oInfo);
return oInfo.Id;
}
public Info GetInfoFromDb(int id)
{
return repository.GetAll().Single(info => info.Id == id);
}
}
// Actual unittests
[Test]
public void SomeRule_InsertInfo_WasInserted() // ex. InsertInfo
{
// Arrange
Info oInfo = new Info();
oInfo.Desc = "Some Description here !!!";
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>();
repositoryMock.Expect(m => m.Save(Arg<Info>.Is.NotNull));
// Act
var savedrecordid = new SomeRule(repositoryMock).InsertInfoToDb(oInfo);
// Assert
repositoryMock.VerifyAllExpectations();
}
[Test]
public void SomeRule_GetInfo_ReciveCorrectInfo() // ex. GetInfo
{
// Arrange
var expectedId = 1;
var expectedInfo = new Info { Id = expectedId, Desc = "Something" };
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>();
repositoryMock.Expect(m => m.GetAll()).Return(new [] { expectedInfo }.AsEnumerable());
// Act
Info receivedInfo = new SomeRule(repositoryMock).GetInfoFromDb(expectedId);
// Assert
repositoryMock.VerifyAllExpectations();
Assert.That(receivedInfo, Is.Not.Null.And.SameAs(expectedInfo));
}
ps: full example availabel here
I'm trying to verify that a method within a mock is called with an expected object parameter. I'm using Moq, nUnit, and thinking that AutoFixture's Likeness should get the job done.
Below is a simplified version of what i'm trying to do.
Is there a way to do this with AutoFixture? Is there a better way to verify that Something is called with the appropriate parameter?
Overriding Equals in the A class to compare the property values and changing the Verify line to:
barMock.Verify(m => m.Something(a));
passes, however I'd rather not override Equals in every class like A in my project.
namespace Test
{
using Moq;
using NUnit.Framework;
using Ploeh.SemanticComparison.Fluent;
public class A
{
public int P1 { get; set; }
}
public interface IBar
{
void Something(A a);
}
public class Foo
{
public A Data { get; private set; }
public void DoSomethingWith(IBar bar)
{
Data = new A { P1 = 1 };
bar.Something(Data);
}
}
[TestFixture]
public class AutoFixtureTest
{
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var a = new A { P1 = 1 };
var expectedA = a.AsSource().OfLikeness<A>();
foo.DoSomethingWith(barMock.Object);
expectedA.ShouldEqual(foo.Data); // passes
barMock.Verify(m => m.Something(expectedA.Value)); // fails
}
}
}
In Verify Moq by default checks reference equality for arguments so it only passes when you provide the same instances (except if you've overriden Equals) in your tests and in your implementation.
In you case the expectedA.Value just returns the new A { P1 = 1 } created in the test which, of course, isn't the same instance created in DoSomethingWith.
You need to use Moq's It.Is construct to properly test this without overriding Equals (in fact for this you don't need Autofixture at all):
barMock.Verify(m => m.Something(It.Is<A>(arg => arg.P1 == a.P1)));
But if you have multiple properties like P1,P2,P3... AutoFixture can be useful:
barMock.Verify(m => m.Something(It.Is<A>(arg => expectedA.Equals(a))));
Because you don't need to write out the equality checks manually for all the properties.
If you upgrade to AutoFixture 2.9.1 (or newer) you can call the CreateProxy method on the Likeness instance which will emit a dynamic proxy for the destination type.
The generated dynamic proxy overrides Equals using Likeness which simplifies the syntax (quite a lot).
Here is the original test method, modified to use the Likeness proxy:
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var expected = new A().AsSource().OfLikeness<A>().CreateProxy();
expected.P1 = 1;
foo.DoSomethingWith(barMock.Object);
Assert.True(expected.Equals(foo.Data)); // passes
barMock.Verify(m => m.Something(expected)); // passes
}
Note that it also makes the test assertion much more specific than accepting Any instance.
You can find more details on this new feature here.