I am getting CS0175 Use of keyword 'base' is not valid in this context error in my unit test case project.
This is how my code looks:
A class which implements a interface
public interface iUtility
{
void Print();
}
public class Utility: iUtility
{
public void Print()
{
Console.Write("Print");
}
}
A base class which uses the utility class and a derived class
public class BaseCls
{
private iUtility _iUtility;
public BaseCls()
{
_iUtility = new Utility();
}
public BaseCls(iUtility iUtility)
{
_iUtility = iUtility;
}
}
public class DerivedCls : BaseCls
{
public void PrintSomething()
{
Console.Write("Print Something");
}
}
In my unit test project, I am testing derived class and trying to pass the instance of utility class. Why I am doing this may not make sense now but I am planning to use unity framework and use IoC to inject different dependencies.
I am not showing all code for brevity.
Error is happening in unit test project
[TestClass]
public class UnitTest1
{
public void TestInitialize()
{
//I want to pass instance of utility class here
iUtility obj = new Utility();
DerivedCls cls = new DerivedCls(): base(obj);
}
[TestMethod]
public void TestMethod1()
{
}
}
What do I need to do to fix this error? I want to pass the instance of utility class from derived class through constructor.
You need to provide a constructor in your derived class.
public class DerivedCls : BaseCls
{
public DerivedCls(iUtility utility) : base(utility) { }
}
Then construct your DerivedCls instances as you normally would: new DerivedCls(someIUtilityInstance)
Related
I have the following simplified pseudocode
class CommonSetup
{
public void CommonSetup()
{
// do stuff once per class
}
public void Foo() { }
}
abstract class BaseTest : IClassFixture<CommonSetup>
{
public void BaseTest(CommonSetup setup)
{
setup.Foo();
}
}
class MyTest : BaseTest
{
// i dont want to have a ctor here
}
I need access to CommonSetup from BaseTest but I don't want MyTest to have a constructor in order to pass CommonSetup through to it because it's pointless boilerplate noise.
Is there a different syntax/mechanism for achieving the same as IClassFixture<> without the need to use constructors to pass the the CommonSetup around?
In my view, it is possible to create a static field to avoid of creation a new object and to share instance across all derived classes.
So let me show an example:
class CommonSetup
{
public CommonSetup()
{
// do stuff once per class
}
public void Foo() { }
}
and:
abstract class BaseTest : IClassFixture<CommonSetup>
{
protected static CommonSetup _commonSetup = new CommonSetup();
public BaseTest()
{
_commonSetup.Foo();
}
}
and your derived classes will not want to have constructor to send parameters for BaseTest class:
class MyTest : BaseTest
{
// There is no need to have constructor to initialize `BaseTest` constructor
}
I have a class A, and a class AStore. My requirement is to prevent all other methods from initializing an instance of class A, which they should get an instance from AStore. In addition, I also need to access the member functions of A from the instance.
Factory pattern is not suitable for this problem as the constructor of A is still public. Ideally, it should throw compilation error when calling the constructor of class A while having access to its member functions.
Can I get C# solutions to this?
For restricting others to create an instance of class A you can use a private constructor and a static factory method to get the instance of that class.
public class A
{
private A(){}
public static A GetInstance()
{
return new A();
}
public void MemberFunctionOfA()
{
// blah blah...
}
}
To enforce instance creation of A only via Astore you can use protected modifier and derive AStore from A. That way, only AStore will have access to its protected members like 'constructor' or 'factory method':
public class Astore : A
{
public A GetInstanceOfA()
{
return base.GetInstance();
}
}
public class A
{
protected A() { }
protected A GetInstance()
{
return new A();
}
public void MemberFunctionOfA()
{
// blah blah...
}
}
//Usage
public class ConsumerClass
{
public void Test()
{
var a = new A(); // Compile error
a = new Astore().GetInstanceOfA();
a.MemberFunctionOfA();
}
}
But there're still chances that another class say 'UnWantedStore' can derive from A and serve instance of A.
Another approach is moving AStore and A classes to the dedicated project and make constructor of A class internal.
// Project A
namespace ProjectA
{
public class A
{
public int PropertyOne { get; set; }
public string PropertyTwo { get; set; }
internal A() {}
}
public class AStore
{
public A CreateA()
{
//internal constructor can be used
return A();
}
}
}
// Project ConsumerOfA
namespace ConsumerOfA
{
public static void UseA()
{
var store = new AStore();
var instanceOfA = store.CreateA();
// have access to the A's public members
}
}
With this approach you will get perfect encapsulation you trying to achive.
Abstract classes to the rescue!
Indeed, there's yet another possible approach! I've never used it but it might work in your scenario. See the following code sample:
public abstract class A
{
public string Text { get; set; }
public string SayHello() => "hello world!";
}
public class AStore
{
private class AInternal : A {}
public void DoStuff()
{
A a = new AInternal();
a.Text = "whatever";
string helloText = a.SayHello();
}
}
Let's explain the approach:
Class A is abstract, therefore it can't be instantiated.
Class AStore implements a private nested class called AInternal which just inherits A to let AStore members be able to instantiate A. Since AInternal is private, no other class than AStore can instantiate AInternal!
Class AStore can access public A members because AInternal inherits A!
You can do this with reflection too:
public class ClassA
{
// The constructor(s) have to be private
private ClassA() { }
// Whatever other code you want
}
public class ClassB
{
public static ClassA GetClassAInstance()
{
// Use reflection to get the private default constructor
ConstructorInfo constructor = typeof(ClassA).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
ClassA instance = constructor.Invoke(new object[] { }) as ClassA;
return instance;
}
}
You can find more information on the GetConstructor method here.
I'm trying to unit test a part of a project; I'm using NUnit. The targeted unit processes objects of several types, all extending a base type. I've created a generic test class on which I set the desired test types:
[TestFixture(typeof(SomeType))]
[TestFixture(typeof(SomeOtherType))]
class MyTestClass<T> where T : SomeBaseType, new()
{
[Test]
public void DoThisTest()
{
var sut = CreateSut();
var target = CreateTarget();
Assert.IsTrue(sut.Process(target));
}
[Test]
public void DoThatTest()
{
var sut = CreateSut();
var target = CreateInvalidTarget();
Assert.IsFalse(sut.IsValid(target));
}
//...
}
This creates a set of all the tests for each type set using TestFixture. For whatever reason, I have a test which only makes sense in the context of a specific type. This means that I need to either 1) use Assert.Ignore() on all other types or 2) create a different test class just for those "special" test cases.
Is there a way of opting out from a test from outside (attribute?) and specify that that particular test must not be "implemented" in certain contexts? I would like to "combine" 1) & 2) such that all the test cases are in the same file/class but some tests are only rendered/implemented/run for certain values set by TestFixture.
This isn't exactly what you're looking for, but I think it's a pretty close work around. You can specify nested classes within your main test fixture and decorate them with different TestFixture attributes to restrict what's run. It's probably best explained with an example. So, given these data types:
public interface ICompetitor {
string GetFinalPosition();
}
public class Winner : ICompetitor{
public string GetFinalPosition() {
return "Won";
}
}
public class Loser : ICompetitor {
public string GetFinalPosition() {
return "Lost";
}
}
I can define these TestFixtures:
[TestFixture(typeof(Winner))]
[TestFixture(typeof(Loser))]
public class CompetitorTests<T> where T : ICompetitor, new()
{
static private T CreateSut() {
return new T();
}
[Test]
public void EverybodyHasPosition() {
Assert.IsNotNullOrEmpty(CreateSut().GetFinalPosition());
}
[TestFixture(typeof(Winner))]
public class WinnerTests {
[Test]
public void TestWon() {
Assert.AreEqual("Won", CompetitorTests<T>.CreateSut().GetFinalPosition());
}
}
[TestFixture(typeof(Loser))]
public class LoserTests {
[Test]
public void TestLost() {
Assert.AreEqual("Lost", CompetitorTests<T>.CreateSut().GetFinalPosition());
}
}
}
The EverybodyHasPosition test is run twice (once for the Winner and once for the Loser classes). Whereas the TestWon is only run for the Winner class and the TestLost is only run for the Loser class. It's not ideal, because you can only access static members of the outer class, and each fixture is responsible for it's own setup/teardown.
You can work around this though, by using a base class. So, the state sharing version might look more like this (notice that each TestFixture inherits from CompetitorTestsState):
public class CompetitorTestsState<T> where T : ICompetitor, new() {
protected T SUT { get; private set; }
[SetUp]
public void Setup() {
SUT = CreateSut();
}
private T CreateSut() {
return new T();
}
}
[TestFixture(typeof(Winner))]
[TestFixture(typeof(Loser))]
public class CompetitorTests<T> : CompetitorTestsState<T> where T : ICompetitor, new() {
[Test]
public void EverybodyHasPosition() {
Assert.IsNotNullOrEmpty(SUT.GetFinalPosition());
}
[TestFixture(typeof(Winner))]
public class WinnerTests : CompetitorTestsState<T>{
[Test]
public void TestWon() {
Assert.AreEqual("Won", SUT.GetFinalPosition());
}
}
[TestFixture(typeof(Loser))]
public class LoserTests : CompetitorTestsState<T>{
[Test]
public void TestLost() {
Assert.AreEqual("Lost", SUT.GetFinalPosition());
}
}
}
I have a concrete class called EventManager and a subclass called ScheduledEventManager. I would like ScheduledEventManager to have to pass the same tests as EventManager plus a few additional ones. Is this possible with xUnit.net?
EDIT: I just realized that my case is a little more complicated than this. I'm using nested classes to keep my tests more organized. Example:
public class EventManagerTests
{
public class WhenAnEventIsFired
{
[Fact]
void ItNotifiesSubscribers()
{
// Perform the test
}
}
}
public class ScheduledEventManagerTests
{
// How to I inherit the above tests since they are in nested classes?
}
It seems to me that this is not possible, but maybe one of you geniuses knows something I don't.
Yes You can:
public abstract class EventManagerTests
{
protected IEventManager _ev;
protected EventManagerTests(IEventManager ev)
{
_ev = ev;
}
[Fact]
public void SharedTest()
{
// Perform _ev test
}
}
public class ScheduledEventManagerTests : EventManagerTests
{
public ScheduledEventManagerTests():base(new ScheduledEventManager())
{
}
// It will inherit tests from the base abstract class
}
public class UnScheduledEventManagerTests : EventManagerTests
{
public UnScheduledEventManagerTests():base(new UnScheduledEventManager())
{
}
// It will inherit tests from the base abstract class
}
Create a parameterized test that takes an instance of your base class as the SUT, and invoke the test with an instance of the sub class. Here's a (contrived) example using NUnit, which results in one passing and one failing test:
public class Foo
{
public virtual int DoSomething()
{
return 10;
}
}
public class Bar : Foo
{
public override int DoSomething()
{
return 9;
}
}
[TestFixture]
public class Tests
{
private Foo[] _foos = { new Foo(), new Bar() };
[Test]
[TestCaseSource("_foos")]
public void When_DoSomething_Is_Invoked_Then_A_Power_Of_Ten_Is_Returned(Foo sut)
{
Assert.That(sut.DoSomething() % 10, Is.EqualTo(0));
}
}
How can a variant of the Template Method pattern be implemented whereby the concrete class does not inherit from the base class, but the overall feature of the pattern is maintained. The reason it cannot inherit is that it's forced to inherit from another class and multiple-inheritance is unavailable.
For example, suppose the following Tempate Method pattern:
public abstract class BaseClass {
public void Alpha() {
Beta();
}
public abstract void Beta();
public void Gamma() {
Delta();
}
public abstract void Delta();
}
public ConcreteClass : BaseClass {
public override void Beta() {
Gamma();
}
public override void Delta() {
Console.WriteLine("Delta");
}
}
...
var object = new ConcreteClass();
object.Alpha(); // will outout "Delta"
How can I achieve the same result without ConcreteClass inheriting BaseClass?
Your base class could depend on an interface (or other type) that's injected via the constructor. Your template method(s) could then use the methods on this interface/type to achieve the pattern's desired outcome:
public class BaseClass
{
IDependent _dependent;
public BaseClass(IDependent dependent)
{
_dependent = dependent;
}
public void Alpha() {
_depdendent.Beta();
}
public void Gamma() {
_depdendent.Delta();
}
}
Effectively using composition rather than inheritance.
You can achieve this by providing a reference to the base class on method call:
public ConcreteClass {
public void Beta(BaseClass baseClass) {
baseClass.Gamma();
}
public void Delta() {
Console.WriteLine("Delta");
}
}